An alternative to global in Python

前端 未结 4 1755
轮回少年
轮回少年 2020-12-19 05:58

I currently have code like this:

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

However, this may

相关标签:
4条回答
  • 2020-12-19 06:32

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

    0 讨论(0)
  • 2020-12-19 06:37
    cache = 1
    def foo():
        return 2
    cache = foo()
    

    or

    d = {'cache': 1}
    def foo(x):
        x['cache'] = 2
    foo(d)
    
    0 讨论(0)
  • 2020-12-19 06:40

    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.

    0 讨论(0)
  • 2020-12-19 06:42
    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.

    0 讨论(0)
提交回复
热议问题