Search code examples
pythonscopenested-function

Strange Scoping in Nested Functions


I have a two nested python functions, which look like this:

def outer():
  t = 0
  def inner():
    t += 1
    print(t)
  inner()

Trying to call outer results in the following error:

>>> outer()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sally.py", line 6, in outer
    inner()
  File "sally.py", line 4, in inner
    t += 1
UnboundLocalError: local variable 't' referenced before assignment

I thought adding the line global t before t += 1 would help, except it didn't.

Why is this happening? How do I get around this problem, other than passing t to inner everytime I call it?


Solution

  • If using python 3, then using the nonlocal keyword would let the interpreter know to use the outer() function's scope for t:

    def outer():
      t = 0
      def inner():
        nonlocal t
        t += 1
        print(t)
      inner()
    


    If using python 2, then you can't directly assign to the variable, or it will make the interpreter create a new variable t which will hide the outer variable. You could pass in a mutable collection and update the first item:

    def outer():
      t = [0]
      def inner():
        t[0] += 1
        print(t[0])
      inner()