I’d like to do something like this, but I get a SyntaxWarning and it doesn’t work as expected
RAWR = "hi"
def test(bool):
if bool:
RAWR = "hello" # make RAWR a new variable, don't reference global in this function
else:
global RAWR
RAWR = "rawr" # reference global variable in this function
print RAWR # if bool, use local, else use global (and modify global)
How do I get this to work? Passing in True or False modifies the global variable.
You cannot. Within a scope, a specific name refers either to a local variable, or to a non-local (e.g. global, or from an outer function) variable. Not both. The
global RAWRline makesRAWRa global for the entire scope (that’s why you get a warning, it doesn’t do what you think it does), just like assignment to a variable makes it local for the entire scope. Edit: Thanks to veredesmarald, we now know it is in fact a syntax error in Python 2. This half of my answer only applies to Python 3 apparently.You should just use a differently-named local variable, and in the branch where you want to “promote” it to a global, set the global and the local variable. (Or just don’t use globals at all.)