The global
keyword is used by the python compiler to mark a name in the function scope as global.
As soon as you use it anywhere in the function, that name is no longer a local name.
Note that if
does not introduce a new scope, only functions and modules do (with classes, list, dict and set comprehensions being a special cases of function scopes).
A (hard to read and non-pythonic) work-around would be to use the globals()
function:
def foo(a):
if a:
globals()['g'] = 10
else:
g = 20