[Tutor] variable scope in nested functions

Kent Johnson kent37 at tds.net
Mon Apr 25 00:02:11 CEST 2005


Logesh Pillay wrote:
> Hello list
> 
> I am having trouble with a variable to act as a counter in a nested 
> recursive function which will only occasionally find an answer.  
> Something like a static variable in C.
> 
> Why does this sort of thing not work?
> 
> def foo (n):
>    counter = 0
>    def choose (i):
>       if (solution found):
>          counter += 1
>          print counter, (solution)
>       else choose (i+1)
>    choose (1)
> 
> I get an error message that counter is referenced before being declared.

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)

You could also write a counter class:
class foo:
    def __init__ (n):
       self.counter = 0
    def choose (self, i):
       if (solution found):
          self.counter += 1
          print self.counter, (solution)
       else self.choose (i+1)

foo().choose (1)

I would suggest separating the counter from the solution checking though.

> 
> Declaring counter as global does not help either

No, then it just looks for counter in the global (module) namespace so it still doesn't find it.

> 
> Incidentally how does one nest comments in python.  I want to comment 
> out part of a line.  Is it just Kate my editor which won't allow it

Use # to comment out to the end of a line. There is no way to comment out the middle of a line (like 
you could do in C or Java with /* stuff */)

Kent



More information about the Tutor mailing list