How do I introspect Python objects with getattr, hasattr, and dir?

· Category: Python Programming

Short answer

Python provides built-in functions for runtime introspection. dir() lists attributes, hasattr() checks for existence, getattr() retrieves values dynamically, and setattr() assigns them.

Steps

  1. Use dir(obj) to discover methods and attributes.
  2. Use hasattr(obj, "attr") before accessing optional attributes.
  3. Use getattr(obj, "attr", default) for safe dynamic access.
class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}"

p = Person("Alice")
print(dir(p))
print(hasattr(p, "name"))       # True
print(getattr(p, "age", 30))    # 30 (default)
method = getattr(p, "greet")
print(method())

Tips

  • inspect module provides advanced introspection: inspect.signature(), inspect.getsource(), inspect.getmro().
  • vars() returns the __dict__ of an object, useful for quick debugging.
  • callable() checks whether an attribute is a function or method.

Common issues

  • dir() returns a list of strings, not the actual attributes; use getattr() to access them.
  • Overriding __dir__ can make introspection misleading.
  • Dynamic attribute access with getattr bypasses static type checking and can hide refactoring errors.