Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

hasattr()

Attempts an attribute lookup and reports whether it finishes without AttributeError.

Version: Python 3.14; repository image, production runtime not attested

Syntax

hasattr(object, name, /)

Attempts an attribute lookup and reports whether it finishes without AttributeError.

Properties are executed during lookup. False means the complete lookup, including any fallback, ended with AttributeError.

The test performs the full lookup and catches a final AttributeError. A class fallback __getattr__ may return a value even after a getter raises AttributeError. On an instance the property getter runs and raises that exception without a fallback, so the first result is False. On the class the property object is retrieved without calling its getter, giving True. Other exception types are not suppressed.

class Sensor:
    @property
    def sample(self): raise AttributeError("offline")
class Recovered(Sensor):
    def __getattr__(self, name): return None
assert hasattr(Recovered(), "sample")
assert hasattr(Sensor, "sample") and not hasattr(Sensor(), "sample")

Examples

class Sensor:
    @property
    def sample(self):
        raise AttributeError("offline")

print(hasattr(Sensor(), "sample"))
print(hasattr(Sensor, "sample"))

Result

False
True

The test performs the full lookup and catches a final AttributeError. A class fallback `__getattr__` may return a value even after a getter raises AttributeError. On an instance the property getter runs and raises that exception without a fallback, so the first result is False. On the class the property object is retrieved without calling its getter, giving True. Other exception types are not suppressed.

Sources