SOME_VARIABLE = []
def some_fun:
append in SOME_VARIABLE
s = []
s = SOME_VARIABLE
SOME_VARIABLE = [] // Not setting to empty list.
return s
How to reset SOME_VARIABLE
to empty.
If you read a variable, Python looks for it in the entire scope chain. This mean that:
GLOB_VAR = "Some string"
def some_fun():
print GLOB_VAR
will print Some string
Now, if you write to a variable, Python looks for it in the local scope, and if it cannot find a variable with the name you gave at the local level, then it creates one.
This means that in your example, you have created a variable named SOME_VARIABLE
local to your some_fun
function, instead of updating the global SOME_VARIABLE
. This is a classic python gotcha.
If you want to write to your global, you have to explicitly tell Python that you are talking about a global variable that already exists. To do so, you need to use the global
keyword. 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 it as a way of encouraging people to keep global variables read-only, or at least to think about what they're doing.
The behaviour is the same (just a bit more surprising) when you try to read first and then write to a global. The 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 a related in-depth post about this that is worth a read for more formal details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With