#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.
Unlike many programming languages, Python does not have block-level scope. That means blocks like conditionals, loops, and pattern matching belong to the scope of the containing function.
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}")
Note: Function parameters are also local variables inside the function.
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()
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}")
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 scopeglobal
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}")