Message24418
Logged In: YES
user_id=593130
No, this issue is not specific to either eval or lambda:
>>> def f(g):
... exec 'def h(x): return g(x)'
... return h
...
>>> f(lambda y: y * 2)(17)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1, in h
NameError: global name 'g' is not defined
It is specific to creating a function at top-level in a separate
execution environment, as done, by design, by both eval and
exec, and with either a def statement or lambda abbreviation
thereof.
In Python, lexical scoping works because nested functions are
compiled along with the outer function, so that scoped variables
can be identified and both functions adjusted so that the coupling
works. In particular, the scoped variable has to not be deleted
when the outer function returns. Eval/exec compile their string
only later, when the function is called.
"it works that way because it is the way it works".
Those are your words, not mine. If you want Python to work
differently, write a PEP or a patch, or raise the question in the
newsgroup/mailing list. I'm done discussing it here. |
|
Date |
User |
Action |
Args |
2007-08-23 14:29:50 | admin | link | issue1153622 messages |
2007-08-23 14:29:50 | admin | create | |
|