Search code examples
pythonpython-3.xmixins

How to reference the attached class from its mixin?


I have the following mixin class and a host class, structured as follow:

class MyMixin:
    @staticmethod
    def preprocessIncomings(bliss, mod, **kw):
        my_logger(f"{__class__} is doing it's job now!")
        ....

class MyAttachedClass(MyMixin):
    ...

To my surprise, the logger doesn't reference to the MyAttachedClass as I intended. Instead it refers to the mixin class MyMixin.

Is there a way to reference to the host class from the mixin static method?


Solution

  • Summarizing the good points in the comments: no, a staticmethod is specifically designed not to give you access to the instance or class from which it gets called, so there is no way to know from within preprocessIncomings that it was called via MyAttachedClass. The __class__ is a local variable, which you could view like a closure (i.e., it is got from the outer scope of where the code is defined).

    You could maybe do more with inspect.stack, but the much more obvious solution is to change the method to a classmethod.