Python Scope
Python · Functions & OOP
Theory
Scope is the region of code where a name (variable) can be seen. Python looks names up using the LEGB rule: Local (inside the current function), Enclosing (inside any outer function, for nested functions), Global (top level of the module) and Built-in (names like len and print). It searches in that order and uses the first match.
Assigning to a name inside a function makes it local to that function by default, even if a global with the same name exists. To change the module-level variable instead, declare global x first; in the example fn() sets the global x to 20, so print(x) shows 20. For nested functions, nonlocal lets the inner function rebind a variable of the enclosing function. Reading a global without assigning to it needs no keyword.
Why we use it
Scope keeps functions independent: variables created inside one function cannot accidentally overwrite variables elsewhere. Knowing LEGB explains surprising errors such as UnboundLocalError.
When to use it
Keep variables local and pass values in through parameters and out through return. Use global sparingly (for constants or simple scripts) and nonlocal for closures; heavy use of globals makes code hard to test.
How it works
- Code uses the name x
- Is x local to this function? Yes: Use the local x. No: Check the enclosing function.
- Found in an enclosing function? Yes: Use the enclosing x. No: Check module globals.
- Found in globals? Yes: Use the global x. No: Check built-ins, else NameError.
- Value of x resolved
Syntax
global variable_nameExample
x = 10
def fn():
global x
x = 20Key points
- Variables defined inside a function are local by default
- global lets a function modify a module-level variable
- Lookup order is Local -> Enclosing -> Global -> Built-in
- nonlocal rebinds a variable of the enclosing function
- Assigning before reading inside a function can raise UnboundLocalError