I would like to create a contextmanager that would intercept any object instantiation from a given class or subclasses of this classes and do something with the object.
I sudo code it could look like something like this:
with my_context_watchdog(my_callback, BaseClass):
obj_1 = BaseClass(name) # launch callback
obj_2 = SubClass(name) # launch callback
obj_3 = RandomClass(name) # does not launch callback
def my_callback(new_obj):
print("new object name:", new_obj.name)
Is there anyway I could do something like this in Python?
The best would be that the callback is executed only after the object has been fully instantiated.
Important: I can't modify any of the object classes, they are in a library I don't have any control on it. I just want to raise a callback when some of the Classes of this library are instantiated.
Maybe the contextmanager is not the best idea, I'm opened to any other solution.