does exec ignore the locals parameter?

C

cburns

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)

% python exec1.py
i=0
j=1

What I really wanted to do was something like:

exec text in globals(), inspect.currentframe(1).f_locals but
that didn't work either.

Thanks,

Charlie
 
B

Benjamin

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)

% python exec1.py
i=0
j=1

What I really wanted to do was something like:

        exec text in globals(), inspect.currentframe(1).f_locals but
that didn't work either.

Trying to modify locals() in a function is undefined behavior.
 
N

Ned Deily

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top