VAR = 123
def func(param=False):
if param:
VAR = 456
return VAR
func(True) # 456
func() # UnboundLocalError: ...
NB: I do not need to change the global variable!
I expect that for the first call the function returns a local variable shadowing the global – that actually works. And for for the second call I expect the function to return the global variable – that leads to exception.
Help me please to understand. Why the interpreter doesn't let me conditionally use both global variable or local?
I suppose that during the second call the local variable shouldn't be declared and so shouldn't shadow the global variable. Then why it leads to exception?