Re: exec within function

2 views
Skip to first unread message

Terry Reedy

unread,
Feb 3, 2010, 2:59:17 PM2/3/10
to pytho...@python.org
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.)

Gerald Britton

unread,
Feb 3, 2010, 3:29:15 PM2/3/10
to Terry Reedy, pytho...@python.org
I get no error:

>>> def a():
... exec('b=1')
... print(b)
...
>>> a()
1
>>>

> --
> http://mail.python.org/mailman/listinfo/python-list
>

--
Gerald Britton

Peter Otten

unread,
Feb 3, 2010, 3:50:38 PM2/3/10
to
Gerald Britton wrote:

> On Wed, Feb 3, 2010 at 2:59 PM, Terry Reedy <tjr...@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

Reply all
Reply to author
Forward
0 new messages