funcs vs vars in global namespace

David Rysdam drysdam at ll.mit.edu
Tue Sep 14 14:06:00 CEST 2004


Getting no answer yesterday, I've done some investigation and I 
obviously don't understand how python namespaces work.  Here's a test 
program:

#!/usr/bin/python

b = 2

def sumWithGlobal(a):
     return a + b

#this is easy
print 'Case 1: Normal function call:'
print sumWithGlobal(2)
print

#If you don't send a globals dict with eval, it uses the one from
#the calling program, so this is basically the same as Case 1
print 'Case 2: Function call from inside an eval using the same globals():'
print eval("sumWithGlobal(2)")
print

#Since I'm sending in a globals dict but haven't included a defintion
#for sumWithGlobal(), obviously this will fail (commented out to get
#past the error)
print 'Case 3: Attempt to replace just the global var b (fails for known 
reason)'
#print eval("sumWithGlobal(2)", {'b':3})
print

#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

#And finally I define both but I still get output as if b = 2
#Again, why?  In the eval's global, b = 3, doesn't it?
print 'Case 5: Attempt to set both function and var.  (var has wrong value)'
print eval("sumWithGlobal(2)", {'sumWithGlobal':sumWithGlobal, 'b':3})
print


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?



More information about the Python-list mailing list