Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 309
Rohan Avatar asked May 03 '12 10:05

Rohan


2 Answers

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.

like image 96
Marcin Avatar answered Nov 15 '22 19:11

Marcin


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.

like image 37
Glider Avatar answered Nov 15 '22 19:11

Glider