Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkey patch __init__ module in Python?

I know, I know, it's dirty and all. I want to know if it's possible to hijack the __init__ module of a Python module to replace it by your own.

I'm asking that because I need to prevent a django lib to start some part of it's init process that make it crashes with our configuration.

And yes, it's better to fix the django lib and send back a patch. Yes, I'm in touch with the author about that. But for now, I need a quick fix.

like image 912
e-satis Avatar asked Oct 13 '22 17:10

e-satis


1 Answers

One way to hijack the import procedure is to simulate the import sometime before it takes place, in another module that is imported before the one you want to monkey-patch. Insert whatever you want into sys.modules with the name of the module as the key, and when the time comes to import the original module, Python will find an entry in sys.modules and will just use that. This may not work if the import is done in some magic way.

On the other hand, you can always just copy the original project and patch it to your liking.

like image 126
Gintautas Miliauskas Avatar answered Oct 18 '22 06:10

Gintautas Miliauskas