Search code examples
pythonclassinheritancemonkeypatching

Effect of Submodules on Monkeypatching of Classes in Python


I have three modules:

in_mod.py

class IN(object):
    def __init__(self):
        print("i am the original IN")

module1.py

from in_mod import IN
class C(object):
    def __init__(self):
        cl = IN()

and module2.py

from module1 import C
class IN2(object):
    def __init__(self):
        print("I am the new IN")

C()

import in_mod
in_mod.IN = IN2
C()

import module1
module1.IN = IN2
C()

I get the desired behaviour of monkey-patching out the IN class and replacing it with the IN2 class when I use module1.IN = IN2.

I would like to understand what the underlying difference between in_mod.IN = IN2 and module1.IN = IN2 is in this context.

I am referencing a related post.


Solution

  • from module import IN creates a local variable that references module.IN; module.IN and IN are two separate references to the same class. IN = IN2 changes the local reference, but module.IN (which is used by module.C) continues to reference the same class.


    UPDATE

    In your edit, module1.IN is a global variable in the module1 namespace that initially refers to a class in in_mod, but is distinct from the global in_mod.IN in the module namespace. Changing its value doesn't affect in_mod at all. There's no way to directly access in_mod's namespace via module1, because you don't import the entire module, just one value from the module.