Functions
Scope & Closures
Complete lesson for Scope & Closures using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Scope & Closures
Section: Functions. Scope and closures in Python — LEGB rule, global / nonlocal, nested functions, closures that remember enclosing state, and common pitfalls with late binding.
What is scope?
- Scope is the region of a program where a name (variable) can be referenced.
- Python resolves names using the LEGB rule: Local → Enclosing → Global → Built-in.
- Assignment in a function makes a name local unless declared
globalornonlocal. - Real-life analogy: a name badge valid only inside a room (local), a floor (enclosing), the building (global), or the city directory (built-in).
| Scope | Where | Example |
|---|---|---|
| Local (L) | Inside the current function | x = 1 in def f(): |
| Enclosing (E) | Outer function of a nested def | def outer(): y = 2; def inner(): ... |
| Global (G) | Module top level | COUNT = 0 at file scope |
| Built-in (B) | Python built-ins | len, print, range, Exception |
LEGB rule in action
- Python looks up a name in that order and stops at the first match.
- If no match is found anywhere, you get
NameError. - Reading a global from a function needs no keyword; assigning to it does (
global).
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("inner:", x)
inner()
print("outer:", x)
outer()
print("module:", x)
# inner: local
# outer: enclosing
# module: global global keyword
- Use
global nameto assign to a module-level name from inside a function. - Without
global, assignment creates a new local that shadows the global. - Prefer returning values or using objects/mutable containers over many globals.
counter = 0
def bump() -> None:
global counter
counter += 1
bump(); bump()
print(counter) # 2 nonlocal keyword
nonlocallets an inner function assign to a name in the nearest enclosing (non-global) scope.- It does not reach the module global; use
globalfor that. - Essential for closures that update enclosing state (counters, accumulators).
def make_counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
c = make_counter()
print(c(), c(), c()) # 1 2 3 What is a closure?
- A closure is an inner function that remembers variables from its enclosing scope even after the outer function has returned.
- Those remembered names are free variables, stored in function cells (
__closure__). - Closures power decorators, callbacks, and lightweight factories without classes.
def make_greeter(greeting: str):
def greeter(name: str) -> str:
return f"{greeting}, {name}!"
return greeter
hi = make_greeter("Hello")
yo = make_greeter("Yo")
print(hi("Ravi")) # Hello, Ravi!
print(yo("Asha")) # Yo, Asha!
print(hi.__closure__[0].cell_contents) # Hello Nested functions vs methods
- A nested
defis just another function object created at runtime when the outer runs. - It is not a method unless attached to a class; it has no automatic
self. - Returning the inner function (or passing it as a callback) is how closures travel.
| Concept | Meaning |
|---|---|
| Nested function | def inside another def |
| Free variable | Name used in inner but bound in enclosing scope |
| Closure | Inner function + remembered enclosing bindings |
| Factory | Outer function that configures and returns a closure |
Name binding rules (read vs write)
- Reading a name from enclosing/global scopes is allowed without keywords.
- Any assignment (
=,+=, annotated assign) to a bare name makes it local for the whole function — unlessglobal/nonlocalis declared. - That is why
x += 1withoutnonlocalraisesUnboundLocalErrorifxonly exists outside.
def broken():
x = 10
def inner():
# UnboundLocalError: x referenced before assignment
# x += 1
pass
inner()
def fixed():
x = 10
def inner():
nonlocal x
x += 1
inner()
return x
print(fixed()) # 11 Built-in scope and shadowing
- Built-ins live in the
builtinsmodule. You can shadow them accidentally (list = [1, 2]). - Shadowing
list,dict,id, orinputbreaks later calls — avoid reusing those names. del list(after shadowing) restores lookup to the built-in if no other binding remains.
Advanced — Scope & Closures
Late-binding closures in loops
- Closures capture variables, not values. Loop variables are looked up when the inner function runs, not when it was defined.
- Classic bug: all lambdas in a list print the final loop value.
- Fix: bind as a default argument (
i=i) or usefunctools.partial.
# Bug: all callables see final i
bad = [lambda: i for i in range(3)]
print([f() for f in bad]) # [2, 2, 2]
# Fix: default-argument binding
good = [lambda i=i: i for i in range(3)]
print([f() for f in good]) # [0, 1, 2] functools.partial as an alternative
partial(func, *args, **kwargs)freezes some arguments without writing a nested def.- Useful for callbacks and for avoiding late-binding bugs cleanly.
from functools import partial
def power(base: int, exp: int) -> int:
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5), cube(5)) # 25 125 Inspecting closures
fn.__code__.co_freevarslists free variable names.fn.__closure__is a tuple of cell objects;.cell_contentsreads the value.- Useful when debugging decorators and factories.
def outer(msg: str):
def inner():
return msg
return inner
f = outer("hi")
print(f.__code__.co_freevars) # ('msg',)
print(f.__closure__[0].cell_contents) # hi Mutable default gotcha vs closures
- A mutable default (
def f(a=[])) is created once at definition time — related but different from closures. - Closures remember enclosing names; defaults bind values at definition.
- Prefer
Nonedefaults and create a new list inside the function.
def append_bad(item, bucket=[]):
bucket.append(item)
return bucket
print(append_bad(1))
print(append_bad(2)) # [1, 2] — shared default
def append_good(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(append_good(1))
print(append_good(2)) # [2] Closures vs classes for state
- A closure with
nonlocalcan replace a tiny class that only stores a few fields and one method. - Prefer a class when you need multiple methods, inheritance, or clear public attributes.
- Prefer a closure for simple factories, decorators, and callbacks.
| Need | Prefer |
|---|---|
| One configured callable | Closure / partial |
| Several methods + attributes | Class |
| Decorator wrapping a function | Closure (nested def) |
| Shared mutable module state | Avoid; use explicit objects |
Scopes in comprehensions and lambdas
- In Python 3, list/dict/set comprehensions and generator expressions have their own local scope for the loop variable.
- Lambdas are ordinary functions: assignment inside them is local; free names resolve via LEGB when called.
x = 10
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # 10 — comprehension did not leak x Tricky Interview Points
Q1) What is the LEGB rule?
Answer Python resolves names in order: Local, Enclosing, Global, Built-in. The first match wins; otherwise NameError.
Q2) What is a closure?
Answer An inner function that remembers free variables from its enclosing scope after the outer function has returned.
Q3) Difference between global and nonlocal?
Answer global targets the module-level name. nonlocal targets the nearest enclosing function scope (not the module).
Q4) Why does x += 1 inside a nested function fail without nonlocal?
Answer Assignment makes x local for the whole function. The local x is read before it is bound, causing UnboundLocalError.
Q5) What is the late-binding closure bug?
Answer Closures capture variables, not values. Functions created in a loop often all see the final loop value when called later. Bind with a default arg (i=i) or use partial.
Q6) How do you inspect free variables of a closure?
Answer fn.__code__.co_freevars for names; fn.__closure__[i].cell_contents for values.
Q7) Can you modify a mutable object from an enclosing scope without nonlocal?
Answer Yes for in-place mutation (list.append, dict[key]=). Rebinding the name itself (xs = []) still needs nonlocal.
Q8) When would you use a closure instead of a class?
Answer When you need a small configured callable or decorator state. Use a class for multiple methods or richer public state.
Q9) Do comprehensions leak their loop variable in Python 3?
Answer No. Comprehension loop variables are local to the comprehension (unlike Python 2 list comps).
Q10) What are free variables?
Answer Names referenced in a function but bound in an enclosing scope, not locally. They are what closures close over.
Q11) Is lambda a special scope?
Answer No. lambda creates a function with the same LEGB rules as def. It is just syntax for a single-expression function.
Q12) How does functools.partial relate to closures?
Answer partial freezes arguments and returns a new callable, often replacing a small nested function that only binds parameters.
Simple Programs
LEGB demo with local shadowing
len = "shadowed" # shadows built-in temporarily (demo only)
def demo():
len = "local"
print("local len:", len)
demo()
print("global len:", len)
del len
print("built-in len:", len([1, 2, 3])) Counter factory with nonlocal
def make_counter(start: int = 0):
n = start
def inc(step: int = 1) -> int:
nonlocal n
n += step
return n
def reset() -> None:
nonlocal n
n = start
inc.reset = reset # type: ignore[attr-defined]
return inc
c = make_counter(10)
print(c(), c(5)) # 11 16
c.reset()
print(c()) # 11 Greeting closure factory
def make_greeter(prefix: str):
def greet(name: str) -> str:
return f"{prefix}, {name}!"
return greet
handlers = [make_greeter(p) for p in ("Hi", "Hello", "Namaste")]
for h in handlers:
print(h("Guru")) Fix late-binding lambdas
from functools import partial
funcs_bad = [lambda: i for i in range(3)]
print("bad:", [f() for f in funcs_bad])
funcs_ok = [lambda i=i: i for i in range(3)]
print("ok:", [f() for f in funcs_ok])
funcs_partial = [partial(lambda i: i, i) for i in range(3)]
print("partial:", [f() for f in funcs_partial]) Running total with mutable cell (no nonlocal)
def make_accumulator():
box = {"total": 0}
def add(x: int) -> int:
box["total"] += x
return box["total"]
return add
acc = make_accumulator()
print(acc(5), acc(3), acc(2)) # 5 8 10 Simple decorator implemented as a closure
import time
def timed(fn):
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
result = fn(*args, **kwargs)
dt = time.perf_counter() - t0
print(f"{fn.__name__} took {dt:.6f}s")
return result
return wrapper
@timed
def work(n: int) -> int:
return sum(range(n))
print(work(100_000)) Enclosing scope vs global assignment
value = "module"
def outer():
value = "outer"
def read():
return value
def write_nonlocal():
nonlocal value
value = "outer-changed"
def write_global():
global value
value = "module-changed"
return read, write_nonlocal, write_global
read, wn, wg = outer()
print(read()) # outer
wn()
print(read()) # outer-changed
wg()
print(value) # module-changed Problem Solving Tricks
- Remember LEGB: Local, Enclosing, Global, Built-in.
- Assignment makes a name local for the entire function — declare
global/nonlocalbefore using it. - Closures capture names, not snapshots; bind loop vars with
i=idefaults. - Mutating a list/dict from an inner function does not need
nonlocal; rebinding does. - Prefer returning values over sprinkling
globalacross a project. - Use
fn.__closure__when a decorator mysteriously remembers the wrong value. - Replace tiny stateful closures with a class if the API grows past one callable.
partialis often clearer than a one-line nested def for freezing arguments.- Never name variables
list,dict,str,id, orinput. - Comprehension variables stay inside the comprehension in Python 3.
Practice Programs List
- Write
make_multiplier(factor)that returns a closure multiplying byfactor. - Implement a bank-account closure with
deposit,withdraw, andbalanceusingnonlocal. - Reproduce the late-binding bug, then fix it three ways (default arg, partial, new function scope).
- Write a
@retry(times=3)decorator as nested functions. - Show
UnboundLocalErrorwithx += 1and fix it withnonlocal. - Inspect
__closure__of a decorator wrapper and print free variable values. - Compare a counter class with a counter closure for the same API.
- Create a list of power functions
n**kfor k in 0..5 without late binding. - Demonstrate shadowing
lenand restoring the built-in withdel. - Rewrite a closure factory using
functools.partialwhere possible. - Explain why
box = []plusbox.appendworks withoutnonlocal. - Build a simple event listener registry with closures.