how to change a function in existing 3rd party library in python

python

Solution

This is called monkey-patching. In short, you can just assign to the variable holding the function:

import existingmodule

existingmodule.foo = lambda *args, **kwargs: "You fail it"

This is rarely the right answer in practice. It's much better to wrap something with your own function, or provide your own implementation elsewhere, or use inheritance (if a method on a class).

The only reason to do this is if you need the altered behaviour to be reflected in the library's own code (or other third party code); if so, test well. It's usually a better approach than just creating your own fork; that said, it might be a good idea to submit your code as a patch, so it's not just you supporting it if it is accepted by the project.

Problem

This was an interview question which was asked to me. Please do not penalize me if it doesn't make sense. She asked: "I have an existing 3rd party lib in python and there is a function foo() in it. How do I modify that function after importing in my existing module?"

Original source

Related problems