scope rules in nested functions

Andrew Collier spambucket at
Sat Jan 29 17:07:17 EST 2005


I was writing a program which used some nested functions, and came 
across a behaviour which I was unable to explain. I can summarise it 
with the example below:

#!/usr/bin/env python

def evalfunction0(a):
    print "Call by eval - Success! arg =",a
def evalfunction3(a):
    def evalfunction1(a):
        string = "evalfunction0(a+1)"
    def evalfunction2(a):
        string = "evalfunction1(a+1)"
# uncomment the next line to make the PREVIOUS line work!
#        evalfunction1(-1)  
    string = "evalfunction2(a+1)"

def callfunction0(a):
    print "Function call - Success! arg =",a
def callfunction3(a):
    def callfunction1(a):
    def callfunction2(a):


What I see (although I've only been able to test it in Python version 
2.3 so far) is that the eval() call in evalfunction2, is unable to 
resolve the symbol name evalfunction1 - even though it would be possible 
to call that function directly. But it is even stranger to me that, if 
evalfunction1() is called directly, then calling that function using 
eval() from the same function also works.

I had previously assumed that the symbols available to eval() would be 
the symbols available as literals, but it seems not. Is this a designed 
feature, and if so would somebody be kind enough to describe why it 

More practically, if there are a large number of functions at the same 
nesting level as evalfunction1(), is it possible for me to allow 
evalfunction2() to access all of them without explicitly naming each one 
as a literal?



 ---       Andrew Collier         ----     To reply by email, please use:
  ---- ---    'andrew {at}'
Have you lost your Marbles?

More information about the Python-list mailing list