4

When a variable/function is defined inside an exec it seems to go to the locals() instead to the globals() how I can change this behaviour? This only happens when you pass the global and local dictionaries to the exec.

Example:

exec("""
a = 2

def foo():
    print a

foo()""") in {},{}

When you try this:

NameError: global name 'a' is not defined

2 Answers 2

2

It's odd to me too at the first glance. But with some more output i found the reason:

>>> g, l = {}, {}
>>> print id(g), id(l)
12311984 12310688
>>>
>>> exec '''
... a = 2
... print 'a' in globals(), 'a' in locals(), id(globals()), id(locals())
... def f():
...     print 'a' in globals(), 'a' in locals(), id(globals()), id(locals())
... f()
... ''' in g, l
False True 12311984 12310688
False False 12311984 12311264

As said in http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as global.

So one solution is use the same dict for globals and locals:

>>> l = {}
>>> exec '''
... a = 2
... def f():
...     print a
... f()
... ''' in l, l
2
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Another solution is then to only pass the global dict. But is good to know the reason.
-1

If a isn't global, make it global...

exec("""
global a
a = 2

def foo():
    print a

foo()""") in {}, {}

2 Comments

Yes, but the code inside the exec is written by a third party that doesn't know that goes inside an exec so they see no reason to use global.
Then why didn't you mention that in the question? I thought you were a beginner (11 rep) that just didn't know about global.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.