Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An alternative to global in Python

Tags:

python

global

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?

like image 264
Yariv Avatar asked Jan 03 '13 08:01

Yariv


People also ask

What can I use instead of globals in Python?

Global mutables (dict, list, and set): (Read more about mutables here.) In short, mutables behave like globals without the global keyword — with the caveat they need to be wrapped in a list, set, or dict with different degrees of readability. You could even use a set.

What can I use instead of a global variable?

In a scenario, where you need one central global point of access across the codebase, singletons are a good alternative for global variables. We can call a singleton as a lazily initialized global class which is useful when you have large objects — memory allocation can be deferred till when it's actually needed.

Is global necessary Python?

It is used to create global variables in python from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.

Why is global not good Python?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.


1 Answers

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.

like image 105
Yariv Avatar answered Nov 05 '22 10:11

Yariv