Using Python global vs version defining module

I wonder if anyone thought about how to use Python global or refer to the module itself. Although in the past I used global when necessary, I found it a bit clearer to make the second method (and recently, this syntax is usually preferred):

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 someone has any strong opinions (which are more pythons, performance, etc.), I would like to hear them.

Btw Ultimately, I use any of them in situations where the module naturally encapsulates all the methods and attributes of what will be a single class, rather than referring to incrementmodule.IncrementClass.counter, I can simply use incrementmodule.counter.

+5
2

global . global - - . sys.modules , , , .

+5
  • : global , ( ).

  • : mod.xxx :

`

import foo
foo.eggs = 'scrambled'

global , mod.xxx .

+3

All Articles