How to change a function in an existing third-party library in python

It was an interview question that they asked me. Please do not punish me if this does not make sense. She asked:

"I have an existing third-party library in python, and it has a foo () function in it. How can I change this function after importing into my existing module?"

+5
source share
2 answers

This is called a monkey patch. In short, you can simply assign a variable holding a function:

import existingmodule

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

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

, , - , ( ); , . , ; , , .

+2

(. fooobar.com/questions/20385/...)

:

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

PyCon 2012 , youtube

, : , , . , script root, root. os.geteuid() == 0. , , geteuid, root, .

- . , , .

+1

All Articles