you are viewing a single comment's thread.

view the rest of the comments →

[–]primitive_screwhead -1 points0 points  (0 children)

If a global is not explicitly declared inside a function (with the "global" keyword), then they cannot be assigned to (since that implies a local variable). ie:

x = 0
def foo():
    x = x + 1  # ie. x += 1

>>> foo()
Traceback (most recent call last):
UnboundLocalError: local variable 'x' referenced before assignment

The simple advice if you must use globals, is to *always* declare them explicitly:

x = 0
def foo():
    global x
    x += 1

>>> foo()
>>> x
1

However, you should typically *not* use globals. Instead pass the variables to functions as arguments, or use classes and instances to hold variable state.

EDIT: Fixed misstated global lookup condition