If you read a variable, Python searches for it in the entire scope chain. It means that:
GLOB_VAR = "Some string" def some_fun(): print GLOB_VAR
will print Some string
Now, if you write a variable, Python searches for it in the local scope, and if it cannot find the variable with the name you specified at the local level, then it creates it.
This means that in your example, you created a variable called SOME_VARIABLE local for your some_fun function instead of updating the global SOME_VARIABLE . This is the classic version of python.
If you want to write your global, you must explicitly tell Python that you are talking about a global variable that already exists. To do this, you need to use the global . So the following:
GLOB_VAR = "Some string" def some_fun(): global GLOB_VAR GLOB_VAR = "Some other string" some_fun() print GLOB_VAR
will print Some other string .
Note. I see this as a way to encourage people to store read-only global variables, or at least think about what they are doing.
The behavior is the same (a bit more surprising) when you first try to read, and then write to the global. Following:
GLOB_VAR = False def some_fun(): if GLOB_VAR: GLOB_VAR = False some_fun()
will raise:
Traceback (most recent call last): File "t.py", line 7, in <module> some_fun() File "t.py", line 4, in some_fun if GLOB_VAR: UnboundLocalError: local variable 'GLOB_VAR' referenced before assignment
because since we will modify GLOB_VAR , it is considered a local variable.
Update: Ely Bendersky has an associated detailed report on this; it is worth reading for more formal details.