Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django: Are there any decorators to tell that input is not none?

Tags:

python

django

  • I am new to Django and come from Java/Spring background.
  • I am wondering if there are decorators something like following that can be done in Django or Python?

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)
  • Since this is something which is pretty easy to get in Java, just looking if Python/Django has it
like image 674
daydreamer Avatar asked Feb 19 '23 20:02

daydreamer


2 Answers

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
like image 68
Jon Clements Avatar answered Feb 22 '23 09:02

Jon Clements


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.

like image 23
Simeon Visser Avatar answered Feb 22 '23 11:02

Simeon Visser