attributespython-3.6getattr

__getattr__ special method


Why does hasattr() return boolean True below? 'bar' attribute is not set anywhere in the code. Thanks

class AttrClass(object):
    def __getattr__(self, name):
        pass


data = AttrClass()
print('Current __dict__:  ', data.__dict__)
print('Does bar exists?:  ', hasattr(data, 'bar'))

Output:

Current __dict__:   {}
Does bar exists?:   True

Solution

  • By overriding the __getattr__ method and making it always return None (since a function that does not explicitly return a value returns None implicitly), instances of AttrClass would now return True for any given name passed to the hasattr function simply because the overridden __getattr__ method does not raise an AttributeError exception, and hasattr only returns false when it gets an AttributeError exception when calling the __getattr__ the method.

    Please refer to the documentation for details.