L3Β·Functions & Modules
πScope & Closures
LEGB rule and functions that capture state.
scopeclosurenonlocalglobal
Β§ 1LEGB
Name lookup order: Local β Enclosing β Global β Built-in.
Β§ 2global vs nonlocal
global rebinds a module-level name. nonlocal rebinds the nearest enclosing function's name.
Β§ 3Closures
A nested function that remembers variables from its enclosing scope, even after that scope returns.
Example
1def make_counter():β2 count = 0β3 def inc():β4 nonlocal countβ5 count += 1β6 return countβ7 return incβ8β9c = make_counter()β10print(c(), c(), c()) # 1 2 3βTry it live Β· Python runs in your browser
Loading playgroundβ¦
Checkpoint quiz
Question 1 / 2
Without 'nonlocal', assigning to 'count' inside inc would: