Search⌘ K
AI Features

Using Functions to Patch a Class

Understand how to use functions to dynamically patch methods on Python classes and objects. Explore the concept and risks of monkey patching, its practical use in testing, and alternatives like subclassing. Gain insight into combining object-oriented and functional techniques for more flexible applications.

Overview

One of the things we noted in the previous example was that mypy assumed that the Callable attribute, callback, was a method of the Task class. This leads to a potentially confusing mypy error message, Invalid self argument "Task" to attribute function "callback" with type "Callable[[int], None]". In the previous example, the callable attribute was emphatically not a method.

The presence of the confusion means that a callable attribute can be treated as a method of a class. Since we can generally supply extra methods to a class, it means we can patch in additional methods at runtime.

Does it mean we should do this? It’s perhaps a bad idea, except in a very special situation.

Example

It is possible to add or change a function to an instantiated object, demonstrated as follows. ...