monkey patch add new class and functions to existing module

Viewed 135

If I have an existing module track.py that looks like:

class A:
   variable_b = "some text"

How can I patch track.py to add a new class and a new function like:

class A:
   variable_b = "some text"

class B:
   variable_c = "more text"

def some_func():
   pass
1 Answers

I think you're saying that track.py is inaccessible (perhaps from a library you don't want to touch).

There's a couple ways you could do it. One is to just import the module then at runtime alter the object to include the class.

import track
track.B = B  # or setattr(track, 'B', B)
track.some_func = some_func  # or settattr(track, 'some_func', some_func)

You could also merge in the __init__.py e.g.

import track
import track_monkey_patch
track.__dict__.update(track_monkey_patch.__dict__)

Also, along the lines of making a decorator or some kind of wrapping to just do it for you, if you are okay adding an external dependency then it looks like someone has done this (never used it myself, just a quick google). https://github.com/christophercrouzet/gorilla

Test code that anyone could use

import collections  # could have been anything just came to my head quickly
def foo():
    print("foooooo")
collections.foo = foo
collections.foo()
>>> foooooo
Related