2

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?

  • 5
    `t` isn't a global variable, you're looking for [`nonlocal t`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal). – Ashwini Chaudhary Mar 20 '17 at 08:49
  • This question (and the accepted answer) are much more concise and informative than the referenced original question. Please keep this one. – fearless_fool Feb 26 '18 at 11:36

1 Answers1

3

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()
Rich
  • 3,781
  • 5
  • 34
  • 56