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:
- Code in the global scope cannot use any local variables.
- However, code in a local scope can access global variables.
- Code in one function’s local scope cannot use variables in any other local scope.
- You can use the same name for different variables if they are in different scopes.
- The
globalStatement: 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
globalkeyword.
def spam():
eggs = 31337 # Local variable
print(eggs)
eggs = 42 # Global variable
spam()
print(eggs) # Prints 42, not 31337