1

Running this code:

import re
regex = re.compile("hello")
number = 0
def test():
  if regex.match("hello"):
    number += 1

test()

Produces this error:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    test()
  File "test.py", line 10, in test
    number += 1
UnboundLocalError: local variable 'number' referenced before assignment

Why can i reference regex from inside the function, but not number?

Jangler
  • 43
  • 2
  • You should also read the python [FAQ](http://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) where this exact question has already been answered. And if you want to know more [here's](http://eli.thegreenplace.net/2011/05/15/understanding-unboundlocalerror-in-python/) an article that does just that. – root Feb 15 '13 at 06:18

1 Answers1

2

Because you're defining a new variable called number inside the function.

Here's what your code effectively does:

def test():
    if regex.match("hello"):
        number = number + 1

When Python first compiles this function, as soon as it sees number =, that makes number into a local. Any reference to number inside that function, no matter where it appears, will refer to the new local. The global is shadowed. So when the function actually executes and you try to compute number + 1, Python consults the local number, which hasn't been assigned a value yet.

This is all due to Python's lack of variable declaration: because you don't declare locals explicitly, they're all declared implicitly at the top of the function.

In this case, you can use global number (on its own line) to tell Python you always want to refer to the global number. But it's often better to avoid needing this in the first place. You want to combine some kind of behavior with some kind of state, and that's exactly what objects are for, so you could just write a small class and only instantiate it once.

Eevee
  • 47,412
  • 11
  • 95
  • 127