Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

monkey patch add new class and functions to existing module

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
like image 204
user3831011 Avatar asked Feb 12 '26 02:02

user3831011


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
like image 74
Andrew Holmgren Avatar answered Feb 13 '26 15:02

Andrew Holmgren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!