Scope & Namespaces
Scope & Namespaces
Section titled “Scope & Namespaces”Python resolves names using the LEGB rule — it searches scopes in this order:
- Local — inside the current function
- Enclosing — any enclosing function scopes (closures)
- Global — module-level
- Built-in — Python’s built-in names (
len,print, etc.)
Local Scope
Section titled “Local Scope”def greet(): message = "Hello" # local to greet() print(message)
greet()# print(message) # NameError — not accessible hereGlobal Scope
Section titled “Global Scope”app_name = "MyApp" # global
def show(): print(app_name) # reads global — OK
show() # "MyApp"global Keyword
Section titled “global Keyword”Required to modify a global variable inside a function:
counter = 0
def increment(): global counter counter += 1
increment()print(counter) # 1Enclosing Scope (Closures)
Section titled “Enclosing Scope (Closures)”def outer(): x = 10
def inner(): print(x) # reads from enclosing scope
inner()
outer() # 10nonlocal Keyword
Section titled “nonlocal Keyword”Modifies a variable in the nearest enclosing (non-global) scope:
def counter(): count = 0
def increment(): nonlocal count count += 1 return count
return increment
c = counter()print(c()) # 1print(c()) # 2print(c()) # 3Namespace vs Scope
Section titled “Namespace vs Scope”- A namespace is a mapping from names to objects (like a dictionary).
- A scope is the textual region where a namespace is directly accessible.
import builtins
# View built-in namesprint(dir(builtins))
# View local/global namespacesdef demo(): local_var = 1 print(locals()) # {'local_var': 1}
print(globals()) # module-level namespaceCommon Pitfall: UnboundLocalError
Section titled “Common Pitfall: UnboundLocalError”x = 10
def bad(): print(x) # UnboundLocalError! x = 20 # Python sees this assignment and treats x as local throughout
# Fix: use global keyword or rename the local variableScope in List Comprehensions (Python 3)
Section titled “Scope in List Comprehensions (Python 3)”In Python 3, comprehension variables are scoped to the comprehension:
result = [i for i in range(5)]# print(i) # NameError in Python 3 (was accessible in Python 2)