scope rules in nested functions
Andrew Collier
spambucket at intensity.org.uk
Sat Jan 29 17:07:17 EST 2005
Hello,
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)"
eval(string)
def evalfunction2(a):
string = "evalfunction1(a+1)"
eval(string)
# uncomment the next line to make the PREVIOUS line work!
# evalfunction1(-1)
string = "evalfunction2(a+1)"
eval(string)
def callfunction0(a):
print "Function call - Success! arg =",a
def callfunction3(a):
def callfunction1(a):
callfunction0(a+1)
def callfunction2(a):
callfunction1(a+1)
callfunction2(a+1)
callfunction3(0)
evalfunction3(0)
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
occurs?
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?
Thanks,
Andrew
--
--- Andrew Collier ---- To reply by email, please use:
---- http://www.intensity.org.uk/ --- 'andrew {at} intensity.org.uk'
--
Have you lost your Marbles? http://www.marillion.com/
More information about the Python-list
mailing list