[Tutor] variable scope in nested functions

Logesh Pillay logesh at iafrica.com
Mon Apr 25 21:30:17 CEST 2005


Thanks Kent for your reply.
You said

>This is a limitation of Python's nested scopes. You can't assign to a variable in an enclosing 
>scope. One way to work around this is to use a mutable value like a list in the enclosing scope:
>def foo (n):
>    counter = [0]
>    def choose (i):
>       if (solution found):
>          counter[0] += 1
>          print counter[0], (solution)
>       else choose (i+1)
>    choose (1)
>
I can't help thinking that this is a little unsatisfactory and suggests 
(with all due respect)  an unfinished quality to Python.

Consider a program I've just translated into python from my version in C.

def erdos(n):                                             #Explores 
Erdos theorem that any
    found, r, s = False, 1, [0]*1000            #integer can be 
expressed as +-1.1
    def choose (d, k):                                  #+-2.2...+-r.r 
for some r and some
        for i in -1, 1:                                       
#combinations of +'s and -'s
            s[d] = i
            if d < r:
                choose (d+1, k - i*d*d)
            elif k == i*d*d:
                found = True
                printout ()
    def printout ():
        print n, '=',
        for i in range (1, r+1):
            if s[i] == 1:
                print '+', i,'.',i,
            else:
                print '-',i,'.',i,
        print '\n'
    while not found:
        choose(1, n)
        r += 1

The program is supposed to return to the python prompt as soon as it 
finds solution(s) at the smallest width r.

I entered it exactly as it is expecting the same sort of error message 
for the boolean variable 'found'.  There was none.  Instead python 
simply fails to perform 'found = True' in choose() and it just keeps 
running (incidentally demonstrating the other part of this Erdos theorem 
that the no. can be  so  expressed  in an infinite number of ways).  
Why  the inconsistency  in handling enclosing scope variables of type 
'int' and 'bool'?  Also, it can't be desirable that the interpreter 
effectively ignores a line of code without warning.

Logesh


More information about the Tutor mailing list