scope rules in nested functions

A

Andrew Collier

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top