0

So there is a class called ClassInOtherCode in module othercode.py that I cannot alter. In othercode.py there is a function called otherfunc() that sometimes instantiates ClassInOtherCode.

Before I run otherfunc() is there a way to tell Python to tell my code via some raised event or call some code of mine when ClassInOtherCode is instantiated?

I am not referring to my code checking if ClassInOtherCode is instantiated after the call to otherfunc(), but rather a push by Python to my code. By push, I am referring to a web pattern whereby the client browser receives info rather than continually asking for it.

My code is not a web app. I'm just trying to make an analogy so my question is hopefully clearer.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
ThomasAJ
  • 723
  • 2
  • 8
  • 17
  • Not sure if I understood correctly, but you could decorate otherfunc to callback your code whenever it is run. You can decorate it from your code when you import otherfunc parent module with a light monkey patching – mozway Oct 13 '21 at 03:50
  • Because you want to do something before ClassInOtherCode is instantiated? In that case I'd look in othercode.py and instantiated it myself before otherfunc() is called, or I'd place some calling code in my __init__..py for my module . Could you provide a more concrete example. – WombatPM Oct 13 '21 at 03:54

1 Answers1

2

You can monkey-patch ClassInOtherCode if you don't have access to its source to add the required functionality to its __init__ method:

from othermodule import otherfunc, ClassInOtherCode

default_init = ClassInOtherCode.__init__

def my_init(*args, **kwargs):
  print("ClassInOtherCode is instantiated!")
  default_init(*args, **kwargs)

ClassInOtherCode.__init__ = my_init

result = otherfunc()  # This should trigger your print statement
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thanks @Selcuk I'll have a play around with that. So to be clear. If something in otherfunc(), or any other code, instantiates ClassInOtherCode, then my_init() will be executed and any parameters supplied to ClassInOtherCode will still arrive to ClassInOtherCode via my_init() ? – ThomasAJ Oct 13 '21 at 04:23
  • 1
    @ThomasAJ That's correct. You are basically modifying its source code dynamically (i.e. for the current process only). – Selcuk Oct 13 '21 at 04:24