Andromeda
Note

Scope (Python)

Definition

The area of a program where a specific variable is “visible” and can be accessed. Variables are stored in either the global scope or a local scope.

Why It Matters

Mastering scope is the only way to avoid ‘spaghetti scripts’ in Python; without it, variables collide in unpredictable ways, leading to ‘ghost bugs’ that are nearly impossible to track down in large codebases.

Core Concepts

  • Global Scope: The area outside all functions. Variables created here exist as long as the program runs and are “forgotten” when it terminates.
  • Local Scope: The area inside a function. Variables created here exist only while the function is executing and are “forgotten” once it returns.
  • The 4 Rules of Scope:
    1. Code in the global scope cannot use any local variables.
    2. However, code in a local scope can access global variables.
    3. Code in one function’s local scope cannot use variables in any other local scope.
    4. You can use the same name for different variables if they are in different scopes.
  • The global Statement: Used inside a function to modify a global variable instead of creating a local one.
  • UnboundLocalError: Occurs if you try to use a local variable before assigning to it, often caused by accidentally “shadowing” a global variable without the global keyword.
def spam():
    eggs = 31337 # Local variable
    print(eggs)

eggs = 42 # Global variable
spam()
print(eggs) # Prints 42, not 31337

Connected Concepts