Content · Programming · Python

Python hasattr() Function: Usage and Examples

Check whether normal attribute lookup succeeds using hasattr().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Check whether normal attribute lookup succeeds using hasattr().

How It Works


hasattr(instance, name) returns a boolean and internally relies on attribute lookup, catching AttributeError. Properties and descriptors can run; it is not a harmless dictionary key inspection.

Prefer a try/except AttributeError around the real operation when races matter.

Step-by-Step Example


class Sensor:
    name = "Temperature"

sensor = Sensor()
print(hasattr(sensor, "name"))
print(hasattr(sensor, "calibration"))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The expression '"Temperature"' supplies the value stored as 'name'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

True
False

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Check which optional methods are available on a small object.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Assuming hasattr() merely scans a raw attribute dictionary without invoking accessors.
  • Checking hasattr() then assuming another thread cannot change the attribute before use.

Key Takeaways


  • Check whether normal attribute lookup succeeds using hasattr().
  • hasattr(instance, name) returns a boolean and internally relies on attribute lookup, catching AttributeError.
  • Prefer a try/except AttributeError around the real operation when races matter.
Share this resourceSend this page to someone who may find it useful.