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: