exec "def.." in globals(), locals() does not work

George Sakkis george.sakkis at gmail.com
Mon Feb 19 23:15:47 EST 2007


On Feb 19, 10:52 pm, xml0... at yahoo.com wrote:
> How do I use exec?

Before you ask this question, the one you should have an answer for is
"why do I (think I) have to use exec ?". At least for the example you
gave, you don't; Python supports local functions and nested scopes,
with no need for exec:

from math import *
G = 1

def d():
  L = 1
  def f(x):
    return L + log(G)
  return f(1)


>python -V
> Python 2.4.3
>
> ----
> from math import *
> G = 1
> def d():
>   L = 1
>   exec "def f(x): return L + log(G) " in globals(), locals()
>   f(1)
> ----
>
> How do I use exec() such that:
> 1. A function defined in exec is available to the local scope (after
> exec returns)
> 2. The defined function f has access to globals (G and log(x) from
> math)
> 3. The defined function f has access to locals (L)
>
> So far I have only been able to get 2 out of the 3 requirements.
> It seems that exec "..." in locals(), globals() only uses the first
> listed scope.
>
> Bottomline:
> exec "..." in globals(), locals(), gets me 1. and 3.
> exec "..." in locals(), globals()  gets me 1. and 2.
> exec "..." in hand-merged copy of the globals and locals dictionaries
> gets me 2. and 3.
>
> How do I get 1. 2. and 3.?

L is local in d() only. As far as f() is concerned, L,G and log are
all globals, only x is local (which you don't use; is this a typo?).
If you insist on using exec (which, again, you have no reason to for
this example), take the union of d's globals and locals as f's
globals, and store f in d's locals():

from math import *
G = 1

def d():
  L = 1
  g = dict(globals())
  g.update(locals())
  exec "def f(x): return L + log(G) " in g, locals()
  return f(1)


George




More information about the Python-list mailing list