Using Functions to Patch a Class

Learn about instance patching in classes and why it may not be beneficial.


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.


It is possible to add or change a function to an instantiated object, demonstrated as follows. First we’ll define a class, A, with a method, show_something():

Get hands-on with 1200+ tech skills courses.