pythonpython-importpython-class

How can I substitute an imported python class in a .py file without modifying the file itself?


What I'd like to achieve is:

b.py(might be in a third party package I cannot modify):

from xxx import A

class B:
    def __init__():
        self.a = A()

The file I actually execute:

execute.py

class A:
    def __init__():
        print("init my own A")

from somepackage.b import B

(do something to substitute A in B with my A above)

b = B()

I want to achieve that, when I run execute.py, use my customized A in b's init, rather than the original A from xxx. And b.py should not be changed. Is there a way to achieve this?


Solution

  • That sounds like you're doing something wrong, but it's easily done with monkey-patching:

    import somepackage.b
    orig_a = somepackage.b.A
    somepackage.b.A = A
    b = somepackage.b.B()
    ...
    somepackage.b.A = orig_a