An alternative to global in Python

元气小坏坏 提交于 2019-12-18 06:09:17

问题


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.



来源:https://stackoverflow.com/questions/14135345/an-alternative-to-global-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!