Skip to content

Local Variable Referenced Before Assignment Python Class Method

The OP wrote (emphasis mine):

The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable.

It is not overriding the global variable. Unless you explicitly specify a variable as global, if there is any assignment to the variable in a function, it is assumed to be local. See also the python tutorial on defining functions where it states (emphasis mine):

More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

and the documentation of the statement (if anyone using Python 3 is looking at this, please also take a look at the (compared to ) very useful statement and its PEP 3104).

To "fix" your code:

Do not use global variables in this way please. @LutzHorn has shown in his answer how to do it right.

The reason to avoid global variables is that their effect is hard to test for, and as soon as code gets complex enough, hard to reason about. If every function modifies global variables instead of properly taking parameters and returning values, understanding what the code actually does is hard as soon as one has more than a week or so of distance from it.

You're trying to assign to a global. Python makes you explicitly do that.

In general this is a pretty good sign that you need to refactor your code until you don't need globals any more.

Note that assignment and access are different beasts - the former requires you to explicitly declare globals, the latter does not. Case in point, your variable is another global but you do not attempt to assign to it, hence python does not complain.

The Programming FAQ goes into more detail:

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.