[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
Ron Adam
ron3200 at gmail.com
Sat Oct 1 22:36:35 CEST 2011
On Sun, 2011-10-02 at 03:57 +0900, Stephen J. Turnbull wrote:
> In fact, it is defined to be equivalent to
>
> bar = deco(foo)
> @bar
> def foo(f):
> return f
>
> Ie,
>
> bar = deco(foo)
> def foo(f):
> return foo
> foo = bar(foo)
>
> (which makes the reason for the error obvious), not
>
> > def foo(f):
> > return f
> > foo = deco(foo)
>
> 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.
Actually, this is what I though it was suppose to be. My example wasn't
very good as it returned valid results in more than one path depending
on how it was called. (not intentionally)
Lets try a clearer example.
def supply_y(y):
def _(func):
def wrapper(x):
return func(x, y)
return wrapper
return _
@supply_y(2)
def add(x, y):
return x + y
Pep 318 says it should translate to ...
def add(x, y):
return x + y
add = supply_y(2)(add)
add(3) ---> 5 # call wrapper with x, which calls add with (x, y)
But the behavior is as you suggest...
_temp = suppy_y(2)
def add(x, y):
return x + y
add = _temp(add)
add(3) ---> 5
This isn't what Pep 318 says it should be.
Is this intentional, and does Pep 318 need updating?
Or an unintended implementation detail?
If it wasn't intended, then what?
Cheers,
Ron
More information about the Python-ideas
mailing list