Python Reference Library →

Python hasattr() Function – Check If an Object Has an Attribute

Let’s look at hasattr() function – check if an object has an attribute

  1. Notice

    hasattr() checks whether attribute lookup succeeds without AttributeError. It does not tell you whether the attribute is callable.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
value = 'tea'
print(hasattr(value, "upper"))
print(hasattr(value, "append"))
Live state

Top-level scope

value→Object 1
Object 1 · str'tea'
This step

hasattr() checks whether attribute lookup succeeds without AttributeError. It does not tell you whether the attribute is callable.

Picture hasattr() function – check if an object has an attribute

hasattr() checks whether attribute lookup succeeds without AttributeError. It does not tell you whether the attribute is callable.

Image brief

Alt text
A diagram for Python hasattr() Function – Check If an Object Has an Attribute. Instructions: value = 'tea' print(hasattr(value, "upper")) print(hasattr(value, "append")). Displayed result: True False. The final example bindings are value --> object 1 (str). object 1: 'tea'
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python hasattr() Function – Check If an Object Has an Attribute". Teaching focus: hasattr() checks whether attribute lookup succeeds without AttributeError. It does not tell you whether the attribute is callable. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS value = 'tea' print(hasattr(value, "upper")) print(hasattr(value, "append")) | v DISPLAYED RESULT True False FINAL BINDINGS value --> object 1 (str) object 1: 'tea' Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python hasattr() Function – Check If an Object Has an Attribute. Instructions: value = 'tea' print(hasattr(value, "upper")) print(hasattr(value, "append")). Displayed result: True False. The final example bindings are value --> object 1 (str). object 1: 'tea'

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
value = 'tea'
print(hasattr(value, "upper"))
print(hasattr(value, "append"))
Live state

Top-level scope

value→Object 1
Object 1 · str'tea'
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
True
False

What do you expect this program to print?

What does this example display?

value = 'tea'
print(hasattr(value, "upper"))
print(hasattr(value, "append"))
What does this example display?
Choose one answer. You can try again.

Answer and explanation

True False

Follow the printed values in order. The output is: True False

More examples and reference

Python hasattr() Function

The hasattr() function in Python is used to check if an object has a specific attribute. It returns True if the attribute exists and False otherwise. This is especially useful when working with dynamic objects or avoiding errors when accessing unknown attributes.

Syntax

hasattr(object, name)

Parameters:

  • object – The object you want to check.
  • name – The name of the attribute (as a string).

Returns:

  • True if the attribute exists.
  • False if it doesn’t exist or raises an AttributeError.

Example: Basic Usage

class Person:
    name = "Alice"

p = Person()
print(hasattr(p, "name"))   # True
print(hasattr(p, "age"))    # False
True
False

Use Case: Avoiding AttributeError

Instead of directly accessing an attribute which may or may not exist, use hasattr() to check first:

if hasattr(p, "name"):
    print(p.name)
else:
    print("No name attribute found")

Example: Working with __dict__ Attributes

class Car:
    def __init__(self):
        self.brand = "Tesla"

c = Car()
print(hasattr(c, "brand"))       # True
print(hasattr(c, "__dict__"))    # True
print(hasattr(c, "model"))       # False
True
True
False

Common Mistakes

  • Passing a non-string as the attribute name will raise a TypeError.
  • Returns False for properties that raise exceptions during lookup.

Interview Tip

hasattr() is commonly used in dynamic programming, frameworks like Django, and when working with JSON-like objects or user-defined classes.

Summary

  • hasattr() checks if an object has an attribute.
  • Returns True or False.
  • Used to prevent AttributeError.
  • Common in introspection and dynamic object handling.

Practice Problem

Create a class Book with a title attribute. Write a program that asks the user for an attribute name and checks whether it exists using hasattr().

class Book:
    def __init__(self):
        self.title = "Python Guide"

b = Book()
attr = input("Enter attribute name to check: ")
if hasattr(b, attr):
    print("Attribute exists")
else:
    print("Attribute does not exist")

What to remember

Connect what you noticed in the example with the idea below.

Remember

hasattr() checks whether attribute lookup succeeds without AttributeError. It does not tell you whether the attribute is callable.

Watch out for this idea

hasattr() always calls the attribute as a method.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →