getattr() is a built-in Python function that dynamically retrieves an attribute from an object by name — the safe, programmatic alternative to dot notation (obj.attr). It supports an optional default value and is essential when attribute names are determined at runtime (from config, user input, data, or reflection). In 2026, getattr() remains a core tool in data science (dynamic column access in pandas/Polars/Dask), software engineering (plugin systems, dependency injection, metaprogramming), and frameworks (FastAPI dependency resolution, SQLAlchemy dynamic attributes, dataclasses runtime checks) — enabling flexible, introspective, and robust code.
Here’s a complete, practical guide to using getattr() in Python: basic attribute access, default values & error handling, real-world patterns (earthquake dynamic column selection, config-driven processing), and modern best practices with type hints, performance, safety, and integration with Dask/Polars/pandas/dataclasses.
Basic getattr() — get attribute by string name, with optional default.
class Earthquake:
def __init__(self):
self.mag = 7.2
self.place = "Japan"
self.depth = 25.0
eq = Earthquake()
print(getattr(eq, 'mag')) # 7.2
print(getattr(eq, 'place')) # Japan
# With default (safe access)
print(getattr(eq, 'time', 'N/A')) # N/A (no AttributeError)
# Dynamic attribute name
attr_name = 'depth'
print(getattr(eq, attr_name)) # 25.0
Real-world pattern: dynamic column access in earthquake DataFrame — from config or user input.
import pandas as pd
df = pd.read_csv('earthquakes.csv')
# Config-driven column selection
columns_to_extract = ['mag', 'place', 'depth', 'time', 'nonexistent']
# Safe extraction with getattr-like behavior
extracted = {}
for col in columns_to_extract:
extracted[col] = df.get(col, pd.Series([None] * len(df))) # pandas .get()
# Or pure getattr style for object attributes
class ReportConfig:
def __init__(self):
self.primary_metric = 'mag'
self.secondary = 'depth'
config = ReportConfig()
primary = getattr(df, config.primary_metric).mean()
secondary = getattr(df, config.secondary).mean()
print(f"Primary ({config.primary_metric}): {primary:.2f}")
print(f"Secondary ({config.secondary}): {secondary:.2f}")
Advanced usage — modules, classes, instances, and custom objects.
import math
# Module attribute
print(getattr(math, 'pi')) # 3.141592653589793
# Class attribute
print(getattr(Earthquake, '__name__')) # Earthquake
# Instance method access
print(getattr(eq, 'mag')) # attribute
# getattr(eq, 'method')() # if method exists
# Custom __getattr__ behavior
class DynamicEarthquake:
def __getattr__(self, name):
if name.startswith('is_'):
attr = name[3:]
return getattr(self, attr) > 6.0
raise AttributeError
deq = DynamicEarthquake()
deq.mag = 7.5
print(deq.is_mag) # True (via __getattr__)
Best practices for getattr() in Python & data workflows. Prefer getattr(obj, 'attr', default) — safe access with fallback. Modern tip: use Polars pl.col(attr) — dynamic column access; Dask ddf[attr] for parallel. Use hasattr() first — check existence before getattr. Add type hints — def get_metric(obj: Any, name: str, default: float = 0.0) -> float. Use getattr() in plugins — dynamic method dispatch. Use getattr() with operator.attrgetter() — attrgetter('mag')(event). Avoid getattr() in tight loops — cache result if repeated. Use vars(obj)/obj.__dict__ — direct dict access alternative. Use inspect.getattr_static() — for static attributes (ignores __getattr__). Use getattr() in metaclasses — dynamic attribute creation. Use getattr(module, func_name)() — dynamic function calls. Use getattr() with dir() — discover attributes. Profile performance — getattr is fast; avoid excessive calls. Use object.__getattribute__ — bypass __getattr__ overrides if needed.
getattr(obj, name[, default]) retrieves attributes dynamically by name — safe access, default fallback, and runtime flexibility. In 2026, use for config-driven code, plugin systems, dynamic column selection in Dask/Polars/pandas, and integrate with dataclasses/Pydantic for runtime introspection. Master getattr(), and you’ll write adaptable, robust, and introspective code when attribute names are not known at write time.
Next time you need to access an attribute whose name you have as a string — use getattr(). It’s Python’s cleanest way to say: “Get this named attribute — even if I don’t know it statically.”