SyntaxWarning: name 'spam' is assigned to before global declaration

September 2005 | Fredrik Lundh

The most common reason for this error is that you’re using multiple global declarations in the same function. Consider this example:

x = 0

def func(a, b, c):
    if a == b:
        global x
        x = 10
    elif b == c:
        global x
        x = 20

If you run this in a recent version of Python, the compiler will issue a SyntaxWarning pointing to the beginning of the func function.

Here’s the right way to write this:

x = 0

def func(a, b, c):
    global x # <- here
    if a == b:
        x = 10
    elif b == c:
        x = 20

For more background, see the Python Language Reference (dead link). Excerpts:

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. (dead link)” (if, while, for, and try does not introduce new blocks).
If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. /…/ The global statement must precede all uses of the name. (dead link)” (throughout the entire block)
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. /…/ Names listed in a global statement must not be used in the same code block textually preceding that global statement. (dead link)

 

A Django site. rendered by a django application. hosted by webfaction.