python local scope
Question: 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`?


Answer: 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.

