Lesson · Python Data Model & Special Methods
Callable Objects
55 min readCallable Objects
Any object with `__call__` is callable. Stateful callable objects are useful when behavior needs configuration or memory while still fitting an API that expects a function-like value.
Learning goals
- Explain what
callable(obj)checks and why adding__call__makes an instance pass it. - Write a class whose instances accept arguments like a function, using
__call__plus configuration from__init__. - Predict the results of
double(10)andcallable(double)in the worked example. - Explain how two instances of the same callable class keep independent state.
- Decide between a stateful callable and a plain function for a strategy-shaped API.
Mental model
The chain runs from a protocol to a design choice: __call__ is the only requirement for callable instances, instance attributes are what let the callable carry configuration between calls, and strategy objects use that shape to swap behavior behind one interface. The decision at the end is whether the behavior needs stored state at all; when it does not, a plain function is the simpler answer.
Mental model
read it top to bottom
__call__ makes an instance callable: double(10) configuration in __init__ carried into every call: self.factor strategy objects one callable interface, swappable behavior plain function the simpler choice when nothing must be remembered
Core idea
The callable protocol is one method wide: any instance whose class defines __call__ accepts ordinary function-call syntax, and every callable shape (functions, methods, classes, callable instances) passes the same callable() check. The worked example's Multiplier turns configuration into behavior: __init__ stores the factor once, and each double(10) call reads it back. That is the trade: a class costs more syntax than a lambda but makes the callable's state explicit, named, and inspectable.
__call__
__call__ makes an instance callable with normal function-call syntax. This is useful for configured strategies, validators, and stateful callbacks.
Stateful callables
A stateful callable keeps information between calls: attributes set in __init__ persist on the instance, so double = Multiplier(2) remembers its factor for every call. Two instances hold independent state, while one shared instance means every caller sees the same updates, so the sharing level is a deliberate decision. The class also makes that state visible and testable, which is the reason to prefer it over a lambda when the callable grows.
Strategy objects
A strategy is interchangeable behavior selected behind one interface. Passing a function or collaborator often expresses this pattern without an inheritance hierarchy.
Function-like classes
Function-like classes are classes whose instances behave as callables, combining function-call syntax with class machinery: named state, additional methods, and a readable repr. They differ from actual functions in visible ways: identity is per instance, attributes can be inspected, and the class itself is callable too, because calling a class runs __init__. Use one when a function-shaped API needs configuration or bookkeeping, and a plain function when it does not.
Walkthrough
Multiplier.__init__storesfactoron the instance, so every instance remembers the configuration its caller chose.__call__acceptsvalueand returnsself.factor * value:double(10)prints20, andMultiplier(3)would create an independent tripler.callable(double)printsTruebecausedouble's class defines__call__;callable(Multiplier)is alsoTrue, but for the different reason that classes themselves are callable.- Predict before running: the two printed lines
20andTrue, and whattype(double)reports about whatdoubleactually is.
Experiments to try
- Create
triple = Multiplier(3)and confirmtriple(10)is30; changetriple.factorand explain whydouble(10)is unaffected. - Delete
__call__temporarily and rerun: record theTypeErrorfromdouble(10)and the valuecallable(double)reports afterwards. - Give
__call__a second parameter with a default, such as a scale, and call the instance with one argument and with two. - Add
__repr__returningf"Multiplier({self.factor})"and check what a list of multipliers shows in the REPL.
Common mistakes
- Reading
callable()as "is a function": it is true for classes, methods, and any instance with__call__, so it says nothing about the object's interface beyond being callable. - Sharing one stateful instance between independent uses, so one caller's updates leak into another's results; create per-use instances or move the state out of the callable.
- Storing call configuration on the class instead of the instance: every instance then shares one value, and rebinding the class attribute changes all of them at once.
- Adding
__call__only to avoid naming a method: the instance-call indirection costs readers more thanmultiplier.multiply(value)when the object is used in one place.
Practice: Easy
- Run the worked example and record both printed lines; then run
type(double)and explain why the result is a class instance rather than a function. - Create
triple = Multiplier(3); recordtriple(10)anddouble(10)and explain how the two instances keep separate factors. - Delete
__call__and rerundouble(10); record the error and the newcallable(double)result.
Practice: Medium
- Build a
Countercallable that increments an internal count on every call and returns the new value; call it three times and explain where that state lives. - Write a function that accepts either a plain function or a callable instance and uses both to transform the same value; explain which form carries configuration more clearly.
- Convert a lambda that captures a factor into a callable class, then convert a callable class back to a function; list which version exposes its state better and which is shorter.
Practice: Hard
- Design a
Validatorcallable class constructed with a minimum and a maximum; its__call__returnsTrueorFalsefor a value. Document the interface and test both boundaries and the values just outside them. - Build a failure lab with two reproductions: a shared callable instance whose mutated configuration changes another caller's results, and call state stored on the class so every instance collides. Explain each mechanism and its fix.
- Connect this lesson to APIs that expect a callable (
sorted(key=...),map): pass the callable instance where a function goes and explain why the protocol, not inheritance, is what makes it fit.
Lesson checklist
- I can explain what
callable()tests and why an instance with__call__passes it. - I can write a callable class that reads configuration from
__init__on every call. - I can predict when two instances share state and when they do not.
- I can choose between a function and a callable class for a strategy-shaped API.
Remember
A callable object is any instance whose class defines `__call__`; the protocol is one method wide, so callables slot into APIs that expect functions. The worked example shows the pattern's point: `Multiplier` turns configuration into a remembered factor, `double(10)` prints `20`, and every instance carries its own independent state. Reach for the class when the callable must remember something; a plain function stays simpler when it must not.
Interview angles
What is the main purpose of **__call__**?+
__call__ makes an instance callable with normal function-call syntax. This is useful for configured strategies, validators, and stateful callbacks.
What should you pay attention to when using **Stateful callables**?+
A stateful callable keeps information between calls, stored on the instance, so double = Multiplier(2) remembers its factor on every call. Two instances hold independent state while one shared instance makes every caller see the same updates, so the sharing level is a deliberate decision.
How does **Strategy objects** fit into this lesson?+
A strategy is interchangeable behavior selected behind one interface. Passing a function or collaborator often expresses this pattern without an inheritance hierarchy.
Why is storing a callable's configuration on the class (rather than the instance) risky?+
Class attributes are shared by every instance, so one update changes what all the others see; if two users of the callable expect independent configuration, results start leaking across them. Instance attributes set in __init__ keep each callable's state separate.