V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wentian
V2EX  ›  Python

[ Python ] @NotNull 装饰器如何写比较好?

  •  
  •   wentian · 2017-06-20 11:05:09 +08:00 · 1396 次点击
    这是一个创建于 2502 天前的主题,其中的信息可能已经有所发展或是发生改变。
    XYxe
        1
    XYxe  
       2017-06-20 13:13:30 +08:00
    一个比较粗略的实现:
    def not_null(*varnames):
    def outer(func):
    def inner(*args, **kwargs):
    args_name = func.__code__.co_varnames
    args_cnt = func.__code__.co_argcount # 没用到
    flag = True
    for name in varnames: # 这里还要考虑 varnames 中有 args 中没有的参数
    index = args_name.index(name) # 还可以加上考虑 kwargs 参数
    flag = flag and (args[index] is not None)
    if not flag:
    raise TypeError('something is None')

    result = func(*args, **kwargs)
    return result
    return inner
    return outer
    XYxe
        2
    XYxe  
       2017-06-20 13:17:37 +08:00
    格式乱了,贴个图吧



    另外在用的时候要:@not_null('param1', 'param2')
    araraloren
        3
    araraloren  
       2017-06-20 14:42:56 +08:00
    @XYxe 返回值也要判断一下,严格的定义肯定实现不了~~
    XYxe
        4
    XYxe  
       2017-06-20 14:59:18 +08:00
    @araraloren #3 哎?判断返回值那检查一下倒数第四行的 result 不就可以了吗?
    araraloren
        5
    araraloren  
       2017-06-20 16:04:41 +08:00
    @XYxe 是的,不要在意后面那句话,我看错了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1055 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 19:03 · PVG 03:03 · LAX 12:03 · JFK 15:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.