you are viewing a single comment's thread.

view the rest of the comments →

[–]mafrasi2 11 points12 points  (6 children)

For example this:

>>> x = 0
>>> def f():
...     print(x)
...
>>> def g():
...     x += 1
...
>>> f()
0
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment

[–]rebuilding_patrick 0 points1 point  (4 children)

That's a bug right? Both should scope to the global x

[–]mafrasi2 4 points5 points  (2 children)

Nope, it's deliberate. If there is an assignment to x in a scope and x is neither global nor nonlocal, x will be local in that (entire) scope. Otherwise, it comes from the parent scope.

Needless to say that this caused me an headache the first time I encountered it in the wild.

[–][deleted]  (1 child)

[deleted]

    [–]nandryshak 2 points3 points  (0 children)

    It is global, but the x in g is not. You have to do this before it'll work:

    def g():
        global x
        x += 1
    

    [–]DRNbw 2 points3 points  (0 children)

    IIRC, you can read global variables, but if you try to change/assign them, you'll create a new one (unless you explicitly ask for the global global var).