Search code examples
pythonattributesinstance

Check if instance of python class has attribute without instantiating the class


Is it possible to check if an instance of a class has an attribute without (being able to) instantiating the class?

Example:

class A where I lack knowledge about arguments to instantiate:

class A:
    def __init__(self, unkown):
        self.a = 1

checking for attribute a in class A fails:

hasattr(A,'a')
>> False

checking for attribute a in instance of class A would succeed:

hasattr(A(1),'a')
>> True

Is it possible to check for attribute a without instantiating A? Maybe with something different than hasattr?


Solution

  • In general this is not possible. You can freely set any attribute on any instance of A at any time. Consider

    a = A('foo')
    setattr(a, input('attr_name: '), 'bar')
    

    A cannot know what attributes may or may not be set on its instances in the future.

    You could do some insane things like parse __init__ if you want to limit the question to attributes set in __init__, but most likely we're having an XY-problem here.