Use __call__ Built-In Function To Create A Stateful Function In Python
The aim of this pageđź“ťis to describe the solution to (an occasional) need for the stateful function The state is usually maintained behind the scenes between calls. Of course, this is usually frowned upon. Prof. Abelson from SICP says:
…the implications of introducing assignment and state into the language are absolutely frightening_
— Lecture 6A: Streams, Part 1 — YouTube
More pragmatically, maintaining local state in functions is also difficult to reason about, test, and debug. However, there are legitimate scenarios such as implementing a caching policy as demoed in the example below. In addition, there are several ways of implementing such stateful functions in python. Here I cover the creation of a callable object with __call__
built-in function.
__call__
allows instances of classes to be callable objects which are called in the exact same way as you call a regular function- the only difference is that in order to call it — you first must instantiate that callable object because the implementation is a class definition
- is invoked on objects when they are called like functions