14

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?"

1
  • Off the top of my head, use a wrapper function. Commented May 3, 2012 at 10:34

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

5

The most common approach would be Monkey patching (See: stackoverflow: what is monkey patching)

For example:

>>> import os
>>> os.listdir('.')
['file_a', 'file_b']
>>> os.listdir = lambda folder: ['nothing in here, nope!']
>>> os.listdir('.')
['nothing in here, nope!']

There was a very good talk on the subject at PyCon 2012 that you can watch on youtube

The talk also gives a very good example of where monkey patching can be useful: Say you have a third party library that does a certain thing. To do it's deed, this script demands to be run as root - but the actual functionality does not require root privileges. Now the third party library might be checking this with os.geteuid() == 0. By monkey patching in your code that uses this library you can override geteuid to fake being root to workaround this limitation.

Using monkey patching is a great way to do a quick fix to a library. Filing a bug report and waiting for a patch might take a while, so you can help yourself this way, without digging into the library source code.

1 Comment

It's not "a great way" to do anything. It's sometimes the only, or the least convoluted way to do something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.