does exec ignore the locals parameter?

Ned Deily nad at acm.org
Thu Jan 22 22:59:39 EST 2009


In article 
<a64d0cdb-13b8-438c-97c0-2f83def7c857 at k1g2000prb.googlegroups.com>,
 Benjamin <musiccomposition at gmail.com> wrote:
> On Jan 22, 6:45 pm, cburns <cburns4... at gmail.com> wrote:
> > In the code below, bar() seems to work, foo() seems broken.
> >
> > % python -V
> > Python 2.6.1
> >
> > % cat exec1.py
> >
> > def foo(i) :
> >         exec "i = i + 1" in locals(), globals()
> >         print "i=%d" % i
> >
> > def bar(j) :
> >         exec "j = j + 1"
> >         print "j=%d" % j
> >
> > foo(0)
> > bar(0)
> Trying to modify locals() in a function is undefined behavior.

BTW, the order of the parameters to exec are reversed; presumably what 
was intended is:

   exec "i = i + 1" in globals(), locals()

That doesn't change the results in question, though, as is, after the 
call to foo(0), i (=1) exists as a global.

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list