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
- Use
dir(obj)to discover methods and attributes. - Use
hasattr(obj, "attr")before accessing optional attributes. - 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
inspectmodule 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; usegetattr()to access them.- Overriding
__dir__can make introspection misleading. - Dynamic attribute access with
getattrbypasses static type checking and can hide refactoring errors.