Home > Mobile >  Conditional shadowing of a global variable
Conditional shadowing of a global variable

Time:05-27

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?

CodePudding user response:

You can't do conditional shadowing. You can use only local variable or only global variable.

And when you use VAR = ... then it automatically assumed that you use local variable.

You have to create other local variable and assign global value or new value.

VAR = 123

def func(param=False):
    result = VAR
    if param:
        result = 456
    return result

print(func(True))  # 456
print(func())      # 123

And frankly, for me this is more readable and doesn't make confusion if I still use local or global variable.

CodePudding user response:

When you define VAR inside the function python thinks that is the "version" of VAR that you want; in other words, you are defining a local inside the "if" statement, so python references that local variable.

def func(param=False):
    if param:
        return VAR
    return VAR

This doesn't cause any issues because you aren't defining the local VAR. When True is passed in it works because you define the local. But since that local is in the function that's what scope it uses.

def func(param=False):
    if param:
        VAR
    return VAR

func()

The code above functions fine because you aren't define a local bound variable.

From the comments on here I Read This and it python is put into byte code then run on a virtual machine. So the variable locations needs to be defined before runtime, then during runtime the interpreter knows which way to go.

  • Related