How to find which superclass contains a name?

40 views Asked by At

I'm working with some code that I didn't write (so don't blame me for the crazyness). This is Python 3.9. I've got:

    try:
        del self.userinfo  # force reload
        if self.userinfo['name'] == self.user():
            self._loginstatus = login.LoginStatus.AS_USER
            return

My first thought was WTF? It deletes self.userinfo and then immediately references it? How can be? Then I realized what must be going on is that self.userinfo is also defined in some superclass, of which there are a bunch:

class APISite(
    BaseSite,
    EchoMixin,
    FlowMixin,
    GeneratorsMixin,
    GeoDataMixin,
    GlobalUsageMixin,
    LinterMixin,
    PageImagesMixin,
    ProofreadPageMixin,
    TextExtractsMixin,
    ThanksFlowMixin,
    ThanksMixin,
    UrlShortenerMixin,
    WikibaseClientMixin,
):

Is there some way to get Python to tell me in which of those superclasses it's finding self.userinfo?

2

There are 2 answers

1
Roy Smith On

Ugh. Nevermind. There's:

@property
def userinfo(self) -> Dict[str, Any]:

and

@userinfo.deleter
def userinfo(self) -> None:
    """Delete cached userinfo.

    .. versionadded:: 5.5
    """
    if hasattr(self, '_userinfo'):
        del self._userinfo

somebody was trying to be clever and fancy.

0
TheTridentGuy supports Ukraine On

Try this code that iterates over all of MyClass's super classes and uses the built-in vars() function to check if the contain the variable name contained in var:

class SuperClass1:
    user_info = 1

class SuperClass2:
    other_var = 2

class MyClass(SuperClass1, SuperClass2):
    @staticmethod
    def find_var(var):
        for superclass in MyClass.__bases__:
            if var in vars(superclass):
                return superclass

test = MyClass()
print(test.find_var("user_info")) # Output: <class '__main__.SuperClass1'>

vars(): https://docs.python.org/3/library/functions.html#vars

class.__bases__: https://docs.python.org/3/library/stdtypes.html?#class.%5F%5Fbases%5F%5F