Reputation: 2414
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.
Upvotes: 5
Views: 497
Reputation: 69021
Performance: using the global
style will be ever so slightly faster, as it only needs one name lookup instead of two (would only matter in a tight loop of many many thousands).
Style: the mod.xxx
style mirrors the way you would access globals from another module that you had imported:
`
import foo
foo.eggs = 'scrambled'
The global
method is more common, but your mod.xxx
method is also easy to understand and very readable.
Upvotes: 3
Reputation: 2519
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.
Upvotes: 5