Confused with Functions and decorators

CHIN Dihedral dihedral88888 at gmail.com
Mon Jul 21 09:30:00 CEST 2014


On Saturday, July 19, 2014 8:44:25 PM UTC+8, Wojciech Giel wrote:
> 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.

Uhn, a local object inside a function
can be passed back in Python.

Of course, a local function is treated
as an object in Python,and the GC is
built-in. 






More information about the Python-list mailing list