Check whether an object has an attribute in Python

Use hasattr and getattr to check Python attributes, retrieve defaults, and handle properties or dynamic lookup without hiding unexpected errors.

Best practices
Python programming and application logging

Use hasattr(obj, "name") when you need a Boolean answer. If you also need the value, getattr(obj, "name", default) performs the lookup once and supplies a fallback when the attribute is missing.

Check or retrieve an attribute

class User:
    def __init__(self):
        self.name = "Tom"

user = User()
print(hasattr(user, "name"))   # True
print(hasattr(user, "email"))  # False
email = getattr(user, "email", "Not set")

An existing attribute whose value is None still exists. The fallback above applies to a missing attribute, not to every false or empty value.

Attribute lookup can run code

hasattr performs attribute lookup and returns False if it raises AttributeError. It does not suppress arbitrary exceptions. A property that raises RuntimeError still raises it through hasattr; a property that accidentally raises AttributeError can look like a missing attribute.

Likewise, __getattr__ can provide attributes dynamically. Whether hasattr returns True depends on whether that method returns a value or raises AttributeError for the requested name. Defining __getattr__ alone does not make every name valid.

Use try/except AttributeError around access when that fits your control flow, but remember that an internal AttributeError may still be ambiguous.

Inspect stored attributes instead

print("name" in vars(user))  # Instance dictionary only
print("name" in dir(user))  # Names reported by dir()

vars() excludes inherited methods and class attributes, and fails for objects without __dict__. dir() is useful for exploration, but custom __dir__ methods and dynamic attributes mean it is not a definitive lookup test.

FAQ

Is getattr faster? If you need the value, it avoids the duplicate lookup of hasattr followed by access. Prefer that simpler behavior rather than assuming a universal timing advantage.

Can I check a module or a method? Yes: hasattr(os, "getenv") works after importing os. For a method, attribute existence alone does not prove callability; callable(getattr(obj, "save", None)) can check that separately.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting