Unexpected behaviour of inner functions/ decorators

David Stanek dstanek at dstanek.com
Tue Jun 30 20:12:40 CEST 2009


On Tue, Jun 30, 2009 at 1:44 PM, Francesco Bochicchio<bieffe62 at gmail.com> wrote:
>

[snip]

> It looks like the decorator uses an older  instance of 'funct', which
> does not yet
> have the attribute dinamically attached to it. This seem to be
> confirmed by the fact that adding the attribute before
> rebinding the function name, the problem disappear:

The decorator is using the original function that you defined. By
decorating 'funct' you are actually rebinding that name to the
'inner_f' function. So the statement 'funct.enabled = True' is
actually creating an enabled property on the 'inner_f' function.

Take a look at this code:

>>> def def_f(f):
...     def inner_f():
...         if iam.enabled:
...             f()
...     iam = inner_f
...     return inner_f
...
>>> @def_f
... def funct():
...     print 'Ciao'
...
>>> funct.enabled = True
>>> funct()
Ciao


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list