Is this possible: scoping question with exec

Emile van Sebille emile at
Fri Aug 24 21:20:27 CEST 2001

>From the Python Reference Manual:

6.13 The exec statement

exec_stmt:    "exec" expression ["in" expression ["," expression]]

This statement supports dynamic execution of Python code. The first
expression should evaluate to either a string, an open file object, or a
code object. If it is a string, the string is parsed as a suite of Python
statements which is then executed (unless a syntax error occurs). If it is
an open file, the file is parsed until EOF and executed. If it is a code
object, it is simply executed.

As far as it being effectively the same as eval, it looks like that to me,
but someone else will have to explain what differences there may be.  I get
similar results for all of:

>>> exec(a.func_code, {'b':4})
>>> eval(a.func_code, {'b':4})
>>> exec a.func_code in {'b':4}

Emile van Sebille
emile at

"Bengt Richter" <bokr at> wrote in message
news:3b86a05d.354015106 at
> On Fri, 24 Aug 2001 07:12:57 -0700, "Emile van Sebille" <emile at>
> > exec(a.func_code, {'b':4})
> >
> That seems to work, but where is that form of exec statement documented?
> Is that form effectively equivalent to eval?
> BTW, I thought this was interesting, to see which global gets
> overridden and which doesn't:
>  >>> def a():
>  ...     print 'a() thinks b is "%s"' % b
>  ...
>  >>> b='from interactive binding'
>  >>> exec """
>  ... print 'exec-ed string thinks a="%s",b="%s"' % (a,b)
>  ... a()
>  ... """ in {'a':a, 'b':'from exec dict'}
>  exec-ed string thinks a="<function a at 007FA77C>",b="from exec dict"
>  a() thinks b is "from interactive binding"
>  >>> exec a.func_code in {'b':'from exec dict'}
>  a() thinks b is "from exec dict"
>  >>>

More information about the Python-list mailing list