Variable scope determines the visibility and lifetime of variable labels. Python resolves variable lookups using the LEGB rule (Local, Enclosing, Global, Built-in).
flowchart TD
A["1. Local Scope (Inside current function/lambda)"] --> B["2. Enclosing Scope (Outer enclosing functions / closures)"]
B --> C["3. Global Scope (Module-level variables)"]
C --> D["4. Built-in Scope (Python built-in keywords/functions: len, print, int)"]
global: Declares that a variable inside a function body refers to the module-level global variable.nonlocal: Declares that a variable inside a nested function refers to a variable in the nearest enclosing non-global scope.# Global Scope Variable
app_status = "INITIALIZING"
def outer_service(service_name: str):
# Enclosing Scope Variable
connection_count = 0
def inner_logger(msg: str) -> None:
nonlocal connection_count # Mutate enclosing variable
connection_count += 1
print(f"[{service_name}] (Log #{connection_count}): {msg}")
return inner_logger
def update_global_status(new_status: str) -> None:
global app_status # Declare intention to modify module global
app_status = new_status
if __name__ == "__main__":
logger = outer_service("AuthService")
logger("User login attempt")
logger("User credentials verified")
print(f"Status before update: {app_status}")
update_global_status("RUNNING")
print(f"Status after update: {app_status}")
global state introduces coupling bugs. Pass parameters and return values explicitly instead.global or nonlocal, Python treats it as a local variable across the entire function body.list, dict, str, id, or input to prevent overwriting Python's built-in namespace.Write a function make_counter() returning an inner function that increments and returns a nonlocal count variable each time it is called.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.