Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's use of global vs specifying the module

Was wondering if anyone had any thoughts on the use of Python's global vs. referencing the module itself. While in the past I used global when needed, I've found it somewhat clearer to do the second method (and recently have tended to favor this syntax):

import sys
mod = sys.modules[__name__]

counter = 0

def incrementGlobal():
    global counter
    counter += 1

def incrementMod():
    mod.counter += 1

Obviously both of them work fine, but if anyone has any strong opinions (what is more pythonic, performance etc), I'd love to hear them.

Btw I end up using either of these in situations where the module naturally encapsulates all the methods and attributes of what would be a single class, and rather than reference incrementmodule.IncrementClass.counter i can just use incrementmodule.counter.

like image 662
gnr Avatar asked Dec 30 '11 13:12

gnr


People also ask

Is it good to use global in Python?

The use of global variable in python is considered bad practice and should generally be avoided. Instead the user can try and use a parameter for passing a value onto a function or return a value to obtain it.

Why should we not use global variables in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.

When should you use global variables in Python?

3. Why Do We Use Global Variables? We can use global variables for many purposes such as for storing constant literal as that improves our program's consistency. Further, since we can access global variables from any function in a program, we need to declare them only once, which shortens our code.

Are Python modules global?

Each Module/file has its own global variable Every command in this Python file can access, read, and modify the value of the variable, that is, it becomes a global variable.


1 Answers

Go with global every time. The global keyword is an obvious and readily recognisable pattern for modifying something at module level. Giving a module a reference to itself from sys.modules seems a needlessly convoluted way of going around it, and is likely to confuse the next programmer who looks at it.

like image 110
dhwthompson Avatar answered Oct 05 '22 23:10

dhwthompson