Bite code
Bite code

Reputation: 597103

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.

Upvotes: 5

Views: 3409

Answers (2)

Gintautas Miliauskas
Gintautas Miliauskas

Reputation: 7892

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.

Upvotes: 4

Rafe Kettler
Rafe Kettler

Reputation: 76965

You can just edit the __init__.py file. There's nothing stopping you and if you do it right nothing bad will happen.

Upvotes: 0

Related Questions