开发者

How to reset 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 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.


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

def some_fun:
    global SOME_VARIABLE
    ...
    SOME_VARIABLE = []


if you don't need the SOME_VARIABLE anymore you could use:

del SOME_VARIABLE

if you want a empty list:

del SOME_VARIABLE[:]


SOME_VARIABLE is global, so rebinding it won't take effect unless you use global. But since it's a mutable object, just mutate it appropriately.

del SOME_VARIABLE[:]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜