Python hasattr() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, hasattr(obj, "name") returns True if obj.name can be read, and False otherwise. It finds instance attributes, class attributes, and methods alike.

It works by calling getattr() and checking whether that raises AttributeError. That makes it a natural tool for duck typing: checking what an object can do (“does it have read?”) instead of what type it is.

hasattr() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass the object and the attribute name.

python
if hasattr(obj, "name"):
    ...
CallWhat it does
hasattr("x", "upper")Returns True.
hasattr(42, "upper")Returns False.
hasattr(obj, "read")Does it behave like a file?
hasattr(Class, "method")Works on classes too.

If you are going to use the attribute right away, getattr(obj, "name", None) or try/except AttributeError avoids looking it up twice.

Library declarations
python
hasattr(object, name, /)

Parameters

ParameterDescription
objectRequired. Any object.
nameRequired. The attribute name as a string.

Return Value

Return ValueDescription
boolTrue if reading the attribute works.

Python Examples

Example 1 — Check Attributes and Methods

Test class attributes, methods, missing names, and built-in values.

python
class Dog:
    sound = "woof"

    def bark(self):
        return self.sound


d = Dog()
print(hasattr(d, "sound"), hasattr(d, "bark"))
print(hasattr(d, "fly"))
print(hasattr("text", "upper"), hasattr(42, "upper"))

How It Works

  1. Class attributes count. sound is defined on the class and found through the instance.
  2. Methods are attributes. bark is found just like data.
  3. Missing names. Dogs have no fly, so the result is False.
  4. Built-in values. Strings have upper; ints do not.

Example 2 — Accept Anything That Can read()

Handle file-like objects and plain lists of strings in one function.

python
import io


def read_all(source):
    if hasattr(source, "read"):
        return source.read()
    return "".join(source)


print(read_all(io.StringIO("from a stream")))
print(read_all(["from ", "a ", "list"]))

How It Works

  1. Ask about behaviour. The function checks for a read method instead of a specific type.
  2. File-like objects. io.StringIO has read(), as do real files.
  3. Fallback. Without read, the source is treated as an iterable of strings and joined.
  4. Open for extension. Any new class with a read() method works without changing the function.

Example 3 — hasattr() Runs Property Code

See how a property that raises AttributeError makes hasattr() report False.

python
class Sensor:
    @property
    def value(self):
        raise AttributeError("not connected")

    @property
    def status(self):
        return "ok"


s = Sensor()
print(hasattr(s, "status"))
print(hasattr(s, "value"))
print(getattr(s, "value", "unknown"))

How It Works

  1. Getter runs. Checking status calls the property, which returns normally.
  2. Error hidden. value exists in the class, but its getter raises AttributeError, so hasattr() says False.
  3. Same rule as getattr. getattr() with a default falls back to "unknown" for the same reason.
  4. Keep getters simple. Raise other exception types for real errors so they are not mistaken for “missing”.

Frequently Asked Questions

hasattr(obj, "name") returns True or False.
Yes. Methods are attributes, so hasattr(obj, "method") is True if it exists.
try/except AttributeError (or getattr with a default) avoids a double lookup when you need the value. hasattr() is fine for simple checks.
If it is a property whose getter raises AttributeError, hasattr() treats it as missing.
Yes. It follows the normal lookup: instance, class, and parent classes.

Next: hash()

Get the hash value used by dicts and sets.

hash() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful