7

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?

Yariv
  • 12,945
  • 19
  • 54
  • 75
  • 1
    What exactly is the pitfall? What are you trying to accomplish, and what is not working? – BrenBarn Jan 03 '13 at 08:30
  • What if someone writes the second method? It will still be a local variable. There is no issue with your code. – ATOzTOA Jan 03 '13 at 08:31
  • 2
    If there's no `global` declaration, then the variable is local - if 'the reader' has any background in python, then they'll know it's local. If you really want to, just add a comment saying it's local or something. – Volatility Jan 03 '13 at 08:35
  • When you have a lot of lines of code, it's cumbersome to have to look for 'global cache' somewhere above 'cache = 2'. I posted a work-around answer. – Yariv Oct 24 '13 at 10:33

4 Answers4

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

Yariv
  • 12,945
  • 19
  • 54
  • 75
8
cache = 1
def foo():
    return 2
cache = foo()

or

d = {'cache': 1}
def foo(x):
    x['cache'] = 2
foo(d)
eumiro
  • 207,213
  • 34
  • 299
  • 261
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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

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.

user1881957
  • 3,258
  • 6
  • 34
  • 42