[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Arnaud Delobelle arnodel at gmail.com
Sat Oct 1 21:27:12 CEST 2011


On 1 October 2011 19:57, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> Ron Adam writes:
[...]
>  > But it seems it's not implemented exactly that way.
>  >
>  > def deco(func):
>  >     def _(f):
>  >         return func(f)
>  >     return _
>  >
>  > @deco(foo)
>  > def foo(f):
>  >     return f
>  >
>  > print(foo('python'))
>  >
>  > Results with ... NameError: name 'foo' is not defined
>

[skip explanation that decorator is evaluated before function definition]

> I guess in theory you could think of moving the evaluation of
> deco(foo) after the def foo, but then the correct equivalent
> expression would be
>
> def foo(f):
>    return f
> foo = deco(foo)(foo)
>
> which I suspect is likely to produce surprising behavior in many
> cases.

Even this wouldn't work, because in reality (in CPython at least) the
name 'foo' is only bound *once*, that is after the application of the
decorator - as the example below illustrates:

>>> def deco(f): return foo
...
>>> @deco
... def foo(): pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in deco
NameError: global name 'foo' is not defined

Anyway, I've now lost track of how this relates to the subject of this thread :)

-- 
Arnaud



More information about the Python-ideas mailing list