The problem is that when a variable appears on the left hand side of the =
operator in a function, such as in
def foo():
started = "fubar"
then the rule is that this variable is a local variable in function foo. It means that if there is another variable in the global namespace, such as
started = False
then these are two different variables, and setting started
in foo()
has no effect on the global variable started
.
There are two main workarounds for this. The first one is a quick and dirty fix: you can add a global
declaration at the very beginning of function foo()
def foo():
global started
started = "fubar"
This works, but it is not good python programming because with more than one variable, it creates obfuscated code. You'll notice that serious python code almost never uses the global statement.
The second workaround is to use object attributes instead of global variables. The code could be written
class Game(object):
def __init__(self):
self.started = False
def foo(self):
self.started = "fubar"
if __name__ == '__main__':
game = Game()
game.foo()
This is by far the preferred way to handle this issue.