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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With