Namespace Mystery (HELP!)

Paul Prescod paul at prescod.net
Fri Jul 7 13:46:04 EDT 2000


"Warren L. DeLano" wrote:
> 
> ...
> 
> Okay, we now know why B doesn't work, but why is it that A doesn't work as
> well?

Dunno. :( I'm surprised that raw "exec" can modify local variables but
then I never use it. I'm one of those anti-exec purists.

> There is a workaround:
> 
> def fn(code):
>     a = 1
>     b = 1
>     my_locals = locals()
>     exec code in my_globals,my_locals
>     return my_locals['a']+my_locals['b']
> 
> which is clearly awkward if you need to do anything more complex with a and
> b...

How about:

def fn(code):
     a = 1
     b = 1
     my_locals = locals()
     exec code in my_globals,my_locals
     a,b=my_locals['a'],my_locals['b']

     *** do whatever you want with a and b ***

exec-based approaches always seem messy to me. I would make code a
function, specify what inputs it should expect and what it outputs. If
it is really wide open, then you could do this:

def fn( code_func ):
    a=1
    b=1
    arg={}
    arg.update( locals() )
    arg.update( globals() )
    out = code_func( arg )
    a,b=out[a],out[b]

But exec wouldn't exist if it were not sometimes the right approach...

-- 
 Paul Prescod - Not encumbered by corporate consensus
Pop stars come and pop stars go, but amid all this change there is one
eternal truth: Whenever Bob Dylan writes a song about a guy, the guy is
guilty as sin.
	- http://www.nj.com/page1/ledger/e2efc7.html




More information about the Python-list mailing list