Search code examples
pythonpython-importmonkeypatching

Python Overlays : A case for monkey Patching


I am trying to wrap/monkey patch modules in python. I am trying to develop a a clean means of implementing this that does not interfere with any existing code.

Problem

Given a script that imports some CLASS from a MODULE

from MODULE import CLASS 

I would like to replace MODULE with another _MODULE_. Where _MODULE_ is a patch for the original MODULE. The cleanest interface I can see for this is as follows.

from overlay import MODULE # Switches MODULE for _MODULE
from MODULE import CLASS   # Original import now uses _MODULE_

This is basically monkey patching modules in the same way one would monkey patch classes, functions and methods. I believe if this is done correctly one could consistently patch code in a project specific kind of way.

What is the best way of implementing this ?


Solution

  • >>> import wrapt
    >>> @wrapt.when_imported('collections')
    ... def hook(collections):
    ...     OldOrderedDict = collections.OrderedDict
    ...     class MyOrderedDict(OldOrderedDict):
    ...         def monkey(self):
    ...             print('ook ook')
    ...     collections.OrderedDict = MyOrderedDict
    ...     
    >>> from collections import OrderedDict
    >>> OrderedDict().monkey()
    ook ook