runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Closure vs callable object

A counter that remembers how many times it was called.

what differs

The closure keeps count in an enclosing scope that only it can reach (nonlocal lets it rebind). The object stores it as an attribute anyone can read or change.

at a glance

approachuse it when
A · closureA small bit of state behind one function.
B · class with __call__The state should be inspectable (c.count), resettable, or there are several related operations.

Watch out: Forgetting nonlocal makes count += 1 raise UnboundLocalError.

the outputs

Each approach runs on the same input.

concepts

closuresnonlocal__call__

learn it

functools.partial: fix some arguments now

related comparisons

Wrapper without wraps vs decorator with functools.wraps · def vs lambda

A · closure
B · class with __call__
Compare Python Approaches · Runtime