Want
def addToList(@not_none a, @not_none b):
# so that I do not check for nullity explicitly
do_things_with_a(a)
do_things_with_b(b)
One doesn't typically constraint data-types in Python. Also, decorators can only be applied to classes and to methods/functions.
Although, you shouldn't really be doing this, this is how you would.
(You could amend this to accept argument names to enforce constraints on with a little work).
def not_none(f):
def func(*args, **kwargs):
if any(arg is None for arg in args):
raise ValueError('function {}: does not take arguments of None'.format(f.__name__))
return f(*args, **kwargs)
return func
@not_none
def test(a, b):
print a, b
You can write a decorator rejectNone
as follows:
def rejectNone(f):
def myF(*args, **kwargs):
if None in args or None in kwargs.values():
raise Exception('One of the arguments passed to {0} is None.'.format(f.__name__)
return f(*args, **kwargs)
return myF
@rejectNone
def f(a, b, k=3):
print a * b
You will now get an Exception
if you try to call f
with a None
argument. Note that decorators can be applied to functions or class methods but you can't put them in front of function parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With