How to reset a global variable in python?

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 delete.

+6
python django
source share
4 answers

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.

+7
source share

You need to tell the interpreter that you are talking about a global variable:

 def some_fun: global SOME_VARIABLE ... SOME_VARIABLE = [] 
+5
source share

if you no longer need SOME_VARIABLE, you can use:

 del SOME_VARIABLE 

if you need an empty list:

 del SOME_VARIABLE[:] 
+2
source share

SOME_VARIABLE is global, so its recovery does not take effect if you do not use global . But since this is a mutable object, just modify it accordingly.

 del SOME_VARIABLE[:] 
0
source share

All Articles