Confused with Functions and decorators

Wojciech Giel wojtekgiel at gmail.com
Sat Jul 19 08:44:25 EDT 2014


On 19/07/14 12:40, Jerry lu wrote:
> oh yeah i forgot about the decorators. Um say that you wanted to decorate a function with the outer() func you would just put @outer on top of it? And this is the same as passing another func into the outer func?
yes.
syntax was added because with very long function definitions it was 
dificult  to track reassignment to the name when it followed definition 
of the function. decorators is just abbreviation.

 >>> def outer(f):
...     def inner(*args, **kwargs):
...         print("inner function")
...         return f(*args, **kwargs)
...     return inner
...
 >>> @outer
... def myfunc(x):
...     print("Myfunc", x)
...
 >>> myfunc("test")
inner function
Myfunc test

it is exactly equivalent to:

 >>> def outer(f):
...     def inner(*args, **kwargs):
...         print("inner function")
...         return f(*args, **kwargs)
...     return inner
...
 >>> def myfunc(x):
...      print("Myfunc", x)
...
 >>> myfunc = outer(myfunc)
 >>> myfunc("test")
inner function
Myfunc test

cheers
Wojciech
>
> and also with the first example you say x is in the scope when is was created can you define x in the outer func and refer to it in the inner func?
check nonlocal.




More information about the Python-list mailing list