David Parks
David Parks

Reputation: 32111

Is `global` the correct way for a class to access a module level variable?

I am creating an enter/exit block for a module level construct. I have the following example to test how to access the module level variable from within the class:

_variableScope = ''

class VariableScope(object):
  def __init__(self, scope):
    self._scope = scope

  def __enter__(self):
    global _variableScope
    _variableScope += self._scope

x = VariableScope('mytest')
x.__enter__()
print(_variableScope)

This gets me the expected value of 'mytest', but ...

Is the use of global inside the __enter__() method correct and good practice?

Upvotes: 0

Views: 76

Answers (1)

Prune
Prune

Reputation: 77910

global is a "code smell": something that indicates undesirable code design. In this case, you're merely trying to create a resource for all instances of a class. The preferred tactic is a class attribute: lift the variable up one level, and all instances will share that single variable:

class VariableScope():
    _variableScope = ''

    def __init__(self, scope):
        self._scope = scope

    def __enter__(self):
        VariableScope._variableScope += self._scope

x = VariableScope('mytest')
x.__enter__()
print(VariableScope._variableScope)

y = VariableScope('add-to-scope')
y.__enter__()
print(VariableScope._variableScope)

Output:

mytest
mytestadd-to-scope

Upvotes: 3

Related Questions