This recipe demonstrates a technique for adding functionality to an existing class method after the class has already been defined.
Requires python 2.1 or later.
Python, 26 lines
This is useful when modifying the behavior of a standard or third party python module when changing the module itself is undesirable.
Also, this recipe can be very handy for debugging, since you can use it to log all calls to a library method that you want to watch (without changing the library code).
Sometimes one needs to globally change the behaviour of an entire third-party python library. For example, a python library that you downloaded has 50 different methods that all return error codes but you want these methods to raise exceptions instead (again, you don't want to change their code). After importing the offending module, you call enhance method to hook in a replacement function that checks the return value and issues an exception if an error occurred.
See also: "Class Adoption" recipe