This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author terry.reedy
Recipients
Date 2005-03-01.17:29:51
SpamBayes Score
Marked as misclassified
Message-id
In-reply-to
Content
Logged In: YES 
user_id=593130

Whoops.  eval('x') ==  x as code snippets has an exception, 
which is the one tripping you up.  When the eval is within a 
function definition (and lambda expressions are abbreviated 
simple function definitions) and 'x' contains a function definition, 
then the body of the contained function definition does not have 
access, when it is run, to the locals of the containing function 
(the lexical scope), whereas it will when x is compiled directly *as 
part of the containing function body*.  eval('x') removes x from 
that part of its context.  eval only has the simple two-level 
globals/locals environment, which can be anything the caller 
passes in, so it compiles x as if it were top-level code.  Hence 
free variables in contained functions are looked up in the global 
passed to  eval when the evaled function is called.

This issue has been discussed on the Python newsgroup/mailing 
list more than once.  If my explanation is not clear, you might be 
able to find others in Google c.l.p archives.  Do consider that 
core functions which have been debugged for over a decade are 
unlike to have many bugs left, although the docs are still being 
improved.

While Python's scoping is lexical, its free variable binding is late.
Consider
>>> def f():
...   x = 0
...   def g(): print x
...   x = 1
...   return g
...
>>> f()()
# What gets printed? 0 or 1?
#  From your comments, I suspect you expect 0.
#  Irregardless, it is
1

Similarly
>>> f()()
1
>>> d={'x': 0}
>>> h=eval('lambda: x', d, d)
>>> h()
0
>>> d['x'] = 1
>>> h()
# now what gets printed?
1
History
Date User Action Args
2007-08-23 14:29:50adminlinkissue1153622 messages
2007-08-23 14:29:50admincreate