funcs vs vars in global namespace

David Rysdam drysdam at ll.mit.edu
Tue Sep 14 09:03:26 EDT 2004


Alex Martelli wrote:
> David Rysdam <drysdam at ll.mit.edu> wrote:
>    ...
> 
>>def sumWithGlobal(a):
>>     return a + b
> 
>    ...
> 
>>#Here is define sumWithGlobals but not b and it still works.  Why?
>>#Shouldn't I get an error that b is undefined, since it isn't in the
>>#globals dict of the eval?
>>print 'Case 4: Attempt to set just the function sumWithGlobal (succeeds
>>for unknown reason'
>>print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal})
>>print
> 
> 
> The function sumWithGlobal, internally, uses the global dictionary of
> the module it was defined in, NOT that of the module it's being called
> from, including the "kinda sorta pseudo" module you have within an eval.
> This also explains:
> 
> 
>>If I add a "print globals()" to sumWithGlobal, I see {'b':2} in there in
>>cases 1, 2, 4 and 5.  What am I doing wrong?
> 
> 
> You're misunderstanding Python globals: they are per-module, not "across
> all modules".
> 
> 
> Alex

OK, I can kind of understand that.  I'm not sure what the point of being 
able to specify the globals for an eval() is then, but if it doesn't do 
what I want it doesn't do what I want.

What I want to do is be able to run multiple scripts that use the same 
global variable and function names but be able to have my master script 
define those variables and functions programmatically.  Can I do that 
with the rexec sandbox stuff?  Or is rexec more about keeping the 
exec()'d code from doing things than specifying precisely what it can do?



More information about the Python-list mailing list