开发者

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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜