On Feb 19, 8:15 pm, "George Sakkis" <[EMAIL PROTECTED]> wrote: > On Feb 19, 10:52 pm, [EMAIL PROTECTED] 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(): >
Thanks! this works. I tried to use g to merge locals and globals But I didn't think of keeping the locals() so that f is visible in d. -- http://mail.python.org/mailman/listinfo/python-list