Use hasattr(obj, "attr_name") to check whether an attribute or method exists on an object, and pair it with callable(getattr(obj, "method_name", None)) when you specifically need to verify that the attribute is an invocable method—or follow Python’s EAFP idiom (try ... except AttributeError:) when calling or reading the attribute immediately afterward.
Basic Example
class FileClient:
timeout = 30
def close(self) -> None:
print("Closed")
client = FileClient()
# 1. Recommended: Check existence of any attribute or method
print(hasattr(client, "timeout")) # Output: True
print(hasattr(client, "close")) # Output: True
print(hasattr(client, "reconnect")) # Output: False
# 2. Verify specifically that an attribute exists AND is a callable method
if callable(getattr(client, "close", None)):
client.close() # Output: Closed
# 3. Pythonic EAFP alternative (avoids double lookup when using the attribute directly)
try:
client.close()
except AttributeError:
pass
Key Details & Edge Cases
hasattr()suppresses exceptions inside@propertygetters (critical trap):- Internally,
hasattr(obj, "name")simply callsgetattr(obj, "name")and returnsFalseif anyAttributeErroris raised—even if the attribute does exist as a@propertywhose internal code raised an unrelatedAttributeError! - If you need to distinguish a missing attribute from a broken
@property, usetry: getattr(obj, "name")or inspectinspect.getattr_static(obj, "name")(which checks the object and its MRO without executing descriptors or@propertycode).
- Internally,
hasattr()returnsTruefor data attributes as well as methods:- Because methods are just callable attributes in Python,
hasattr(obj, "timeout")returnsTruefor anintfield (30). Attemptingobj.timeout()afterward raisesTypeError: 'int' object is not callable. - Always combine
getattrwithcallable()(callable(getattr(obj, "close", None))) before invoking a dynamic method name.
- Because methods are just callable attributes in Python,
- Triggering side effects or lazy loading (
__getattr__/@property):- Because
hasattr()actually evaluatesgetattr(), callinghasattr(obj, "expensive_prop")executes the@propertycomputation or triggers ORM/proxy lazy network/database loading. Useinspect.getattr_static(obj, "expensive_prop", None) is not Nonewhen you must inspect structure without triggering side effects.
- Because
- Avoid
dir(obj)for attribute checks ("x" in dir(obj)):"x" in dir(obj)is slow (it allocates and sorts a list of all attribute strings), can miss dynamic attributes handled by__getattr__, and can be tricked if a class overrides__dir__. Always preferhasattr()orgetattr(..., sentinel).
- Single-lookup optimization with a unique sentinel (
_MISSING = object()):- Instead of calling
hasattr(obj, "x")followed bygetattr(obj, "x")(which performs two dictionary/descriptor lookups), fetch once with a sentinel:_MISSING = object() val = getattr(client, "timeout", _MISSING) if val is not _MISSING: print(val)
- Instead of calling
Comparison of Attribute & Method Inspection Methods in Python
| Method | Syntax | Distinguishes Methods from Fields? | Executes @property / __getattr__? |
Best Used When |
|---|---|---|---|---|
hasattr(obj, name) |
hasattr(obj, "close") |
No (returns True for both) |
Yes | Simple boolean guard checking whether an attribute or method name is present. |
callable(getattr(...)) |
callable(getattr(obj, "close", None)) |
Yes (True only if invocable) |
Yes | Safely checking that a method exists before calling it dynamically. |
EAFP (try / except) |
try: obj.close() except AttributeError: |
Fails with TypeError if not callable |
Yes | Idiomatic Python duck typing when calling the method directly in the hot path. |
getattr(obj, name, default) |
val = getattr(obj, "timeout", 10) |
No | Yes | Reading an optional attribute with a fallback value in a single lookup. |
inspect.getattr_static() |
inspect.getattr_static(obj, "prop", None) |
No (returns raw descriptor/function) | No (zero side effects) | Inspecting proxies, ORMs, or @property attributes without triggering evaluation. |
You must log in or register to comment.
