hasattr() is a built-in Python function that checks whether an object has a named attribute — returning True if the attribute exists (including via __getattr__), and False otherwise. It’s the safe, dynamic way to test for attribute presence without raising AttributeError, making it essential for introspection, plugin systems, dynamic configuration, and defensive programming. In 2026, hasattr() remains a core tool in data science (checking DataFrame columns, model attributes), software engineering (API compatibility checks, optional dependencies), and frameworks (FastAPI route validation, SQLAlchemy model introspection) — enabling robust, runtime-adaptive code.
Here’s a complete, practical guide to using hasattr() in Python: basic checks, default handling, real-world patterns (earthquake data column validation, dynamic attribute access), and modern best practices with type hints, performance, safety, and integration with Dask/Polars/pandas/dataclasses/inspect.
Basic hasattr() — check attribute existence without errors.
class Earthquake:
def __init__(self):
self.mag = 7.2
self.place = "Japan"
eq = Earthquake()
print(hasattr(eq, 'mag')) # True
print(hasattr(eq, 'depth')) # False
print(hasattr(eq, '__dict__')) # True (built-in attribute)
# Safe access pattern
if hasattr(eq, 'depth'):
print(eq.depth)
else:
print("No depth available")
Real-world pattern: validating & dynamically accessing columns in earthquake DataFrame.
import pandas as pd
df = pd.read_csv('earthquakes.csv')
required_cols = ['time', 'latitude', 'longitude', 'mag', 'depth', 'place']
# Check missing columns
missing = [col for col in required_cols if not hasattr(df, col) and col not in df.columns]
if missing:
print(f"Missing columns: {missing}")
else:
print("All required columns present")
# Dynamic column selection from config
config_cols = ['mag', 'place', 'depth', 'nonexistent']
available_cols = [col for col in config_cols if col in df.columns or hasattr(df, col)]
subset = df[available_cols]
print(subset.head())
# Polars version (column existence check)
import polars as pl
pl_df = pl.read_csv('earthquakes.csv')
print(pl_df.select(pl.col('mag').is_not_null()).any()) # True if any non-null
Advanced usage — modules, custom __getattr__, and dynamic dispatch.
import math
# Module attribute check
print(hasattr(math, 'pi')) # True
print(hasattr(math, 'tau')) # False
# Custom __getattr__ behavior
class DynamicEarthquake:
def __getattr__(self, name):
if name.startswith('is_'):
attr = name[3:]
return getattr(self, attr, 0) > 6.0
raise AttributeError
deq = DynamicEarthquake()
deq.mag = 7.5
print(hasattr(deq, 'is_mag')) # True (via __getattr__)
print(hasattr(deq, 'nonexistent')) # False
Best practices for hasattr() in Python & data workflows. Prefer hasattr(obj, name) — over name in dir(obj) (faster, handles __getattr__). Modern tip: use Polars col in df.columns — for column existence; Dask col in ddf.columns. Combine with getattr(obj, name, default) — safe access pattern. Add type hints — def has_prop(obj: Any, name: str) -> bool. Use hasattr() in plugins — check if plugin has hook method. Use hasattr() with operator.attrgetter — attrgetter('mag')(event) if hasattr(event, 'mag') else None. Avoid hasattr() in tight loops — cache result. Use vars(obj) — faster dict check if object has __dict__. Use inspect.getattr_static(obj, name) — ignores __getattr__ (static check). Use hasattr() in metaclasses — dynamic attribute validation. Use hasattr(module, 'function_name') — dynamic import checks. Use hasattr(type(obj), 'method_name') — check class methods. Profile performance — hasattr() is fast; avoid excessive calls. Use object.__getattribute__ — bypass overrides if needed.
hasattr(obj, name) checks for attribute existence — safe, handles __getattr__, returns True/False without raising errors. In 2026, use for dynamic attribute access, plugin validation, column checks in Dask/Polars/pandas, and integrate with dataclasses/Pydantic for runtime introspection. Master hasattr(), and you’ll write adaptable, robust, and error-resistant code when dealing with dynamic or unknown attributes.
Next time you need to safely check for an attribute — use hasattr(). It’s Python’s cleanest way to say: “Does this object have this attribute? — tell me without crashing.”