funcs vs vars in global namespace

Alex Martelli aleaxit at yahoo.com
Tue Sep 14 08:41:34 EDT 2004


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



More information about the Python-list mailing list