[Python] How to write @NotNull decorator better?
漂亮男人
漂亮男人 2017-06-22 11:51:47
0
2
865

Actual Phenomenon

  1. @NotNull, @Nullable (by jetbrains) in Java: https://www.jetbrains.com/hel...

  2. It can be implemented using decorators in Python, but no fine-grained control has been found yet: https://www.google.com/search...

Expected Phenomenon

  1. Hope to provide a kind of fine-grained control, that is: specific control of each parameter

  2. Only want to check the null pointer, no type qualification

Related codes

  • Manual, cumbersome writing method

def func(param1, param2, param3):
    # 明确表示, 不接受空指针(这里写法很繁琐, 是否有简化方法?)
    if not ((param1 is not None) and (param2 is not None) and (param3 is not None)):
        raise TypeError('%s or %s or %s is None' % (param1, param2, param3))

    # 正常函数逻辑
  • How to write the decorator (not implemented)

@not_null(param1, param2)
def func(param1, param2, param3, *args, **kw):

Context

  • Python 3.5

漂亮男人
漂亮男人

reply all(2)
習慣沉默
from functools import wraps
def allow_jsonp(fun):
    @wraps(fun)
    def wrapper_fun(*args, **kwargs):
        for a in args:
            if not a:
                return 'args is null'
        return fun(*args, **kwargs)
    return wrapper_fun

@allow_jsonp
def a(a):
    print (111111111)

print (a(0))
洪涛
from functools import wraps

def not_none(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if (None in args) or (None in kwargs.values()):
            raise ValueError('Arguments must be not None')
        else:
            return func(*args, **kwargs)
    return wrapper
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template