exec within function

Peter Otten __peter__ at web.de
Wed Feb 3 15:50:38 EST 2010


Gerald Britton wrote:

> On Wed, Feb 3, 2010 at 2:59 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>> On 2/3/2010 3:30 AM, Simon zack wrote:
>>>
>>> hi,
>>> I'm not sure how I can use exec within a function correctly
>>> here is the code i'm using:
>>>
>>> def a():
>>> exec('b=1')
>>> print(b)
>>>
>>> a()
>>>
>>> this will raise an error, but I would like to see it outputting 1
>>
>> Always **copy and paste** **complete error tracebacks** when asking a
>> question like this. (The only exception would be if it is v e r y long,
>> as with hitting the recursion depth limit of 1000.)

> I get no error:
> 
>>>> def a():
> ...  exec('b=1')
> ...  print(b)
> ...
>>>> a()
> 1

My crystal ball says you're using Python 2.x. Try it again, this time in 
3.x:
 
Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     exec('a = 42')
...     print(a)
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
NameError: global name 'a' is not defined

OP: Python 2.x generates different bytecode for functions containing an exec 
statement. In 3.x this statement is gone and exec() has become a normal 
function. I suppose you now have to pass a namespace explicitly:


>>> def f():
...     ns = {}
...     exec("a=1", ns)
...     print(ns["a"])
...
>>> f()
1

Peter



More information about the Python-list mailing list