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)