About 2464 letters

About 12 minutes

#Python's scope

In Python, scope refers to the region where a variable is valid. Every code block in Python has its own scope.

Variables created inside a code block are only valid within that block and are called local variables.

The outermost code block's scope is called the global scope, and variables in the global scope are called global variables.

For example:

def attack(attack_power: float, defense_power: float) -> float:
    # damage is a local variable inside attack function
    damage: float = attack_power * (1 - defense_power / (defense_power + 100))

    # return damage
    return damage

# damage variable does not exist outside the function, so this will cause an error
print(f"Damage is {damage}")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

An inner scope, being part of an outer scope, can access variables from the outer scope:

value: int = 233

def func():
    print(f"value is {value}")

func()

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

However, if an inner scope assigns a variable with the same name as an outer scope variable, it creates a new local variable in the inner scope instead of modifying the outer variable. This new local variable is called a shadow variable:

value: int = 233

def func():
    value = 100  # Creates a new local variable, does not modify outer variable
    print(f"Inner value is {value}")

func()
print(f"Outer value is {value}")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

To modify an outer scope variable from an inner scope, you need to use the nonlocal or global keyword:

  • nonlocal looks up one level of outer scope, but cannot target the global scope
  • global refers to the global scope
# Global variable
value: int = 233

def outer_func():
    # Local variable in outer_func
    value: int = 666

    def inner_func():
        nonlocal value  # Refers to outer_func's variable
        value = 100    # Modify the outer variable
        print(f"value in inner_func is {value}")

    inner_func()
    print(f"value in outer_func is {value}")

outer_func()

print(f"value in global scope is {value}")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025