An alternative to global in Python

2020-02-12 06:45发布

问题:

I currently have code like this:

cache = 1
def foo():
    global cache
    # many
    # lines
    # of code
    cache = 2

However, this may lead to hard-to-find-bugs in the future, because the reader may not notice that global cache appears somewhere above cache = 2. Alternatively, a contributor may mistakenly add def bar(): cache = 2 and forget to add the global cache.

How can I avoid this pitfall?

回答1:

class Cache:
     myvar = 1

def foo():
    Cache.myvar = 2

This way, Cache.myvar is practically a "global". It's possible to read/write to it from anywhere.

I prefer this over the dictionary alternative, because it allows for auto-complete of the variable names.



回答2:

cache = 1
def foo():
    return 2
cache = foo()

or

d = {'cache': 1}
def foo(x):
    x['cache'] = 2
foo(d)


回答3:

"the reader may unintentionally think that the global variable has been updated" isn't much of a pitfall. You have to expect that people reading your code know how Python works. If you want to make it extra clear, use a comment. That's what they're for.



回答4:

Using global variable is not a good programming practice. Pass the variable as an argument: make function returns something and use it in another function. Function can be assignment to variable that's how Python works.



标签: python global