[Tutor] Decorators: Are they good for checking inputs and outputs?

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Jan 7 01:24:16 CET 2013


On 7 January 2013 00:13, DoanVietTrungAtGmail <doanviettrung at gmail.com> wrote:
> .. Could you perhaps give a concrete example of a situation where a
> decorator would be useful for checking the inputs to a function? .. Oscar
>
> Say I write a function that expects 5 positional arguments, and up to 4 **
> arguments. Now I want to:
> a- check that the first positional argument is a sorted list. If not a list,
> raise an error. If an unsorted list, sort it and pass to the function
> b- check that the 5th position argument is an 0 < int < 10
> c- check that no more than 4 ** arguments are passed

Is there not a contradiction between the points b and c? In any case,
checking the number of arguments is not something that normally needs
to be done in Python code, e.g.:

def my_function(arg1, arg1):
    # Raises an error when called with the wrong number of args
    pass

>
> In the decorators-make-my-life-simple scenario I hope for, I'll simply open
> my box of decorators, pick 3 relevant decorators, and put the 3 @ lines
> above my function. In the @ for the b- test, I'll pass a 5 to tell the
> decorator to look at the 5th argument, and similarly a 4 for the decorator
> checking c-.

How is that better than doing the same within the function? I would
say that checking the validity of the arguments inside the function is
generally clearer to read than adding the checks with decorators. How
would a decorator do better than the following?

def myfun(a, b, c, d, e):
    a.sort()
    if not (0 < e < 10) and int(e) == e:
        raise ValueError('e should be integer 1-9: %s' % e)
    # And now the function body
    pass


Oscar


More information about the Tutor mailing list