Can I add custom methods/attributes to built-in Python types?

You can’t directly add the method to the original type. However, you can subclass the type then substitute it in the built-in/global namespace, which achieves most of the effect desired. Unfortunately, objects created by literal syntax will continue to be of the vanilla type and won’t have your new methods/attributes. Here’s what it looks like … Read more

Can I patch a Python decorator before it wraps a function?

It should be noted that several of the answers here will patch the decorator for the entire test session rather than a single test instance; which may be undesirable. Here’s how to patch a decorator that only persists through a single test. Our unit to be tested with the undesired decorator: # app/uut.py from app.decorators … Read more

When monkey patching an instance method, can you call the overridden method from the new implementation?

EDIT: It has been 9 years since I originally wrote this answer, and it deserves some cosmetic surgery to keep it current. You can see the last version before the edit here. You can’t call the overwritten method by name or keyword. That’s one of the many reasons why monkey patching should be avoided and … Read more

What is monkey patching?

No, it’s not like any of those things. It’s simply the dynamic replacement of attributes at runtime. For instance, consider a class that has a method get_data. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, … Read more