Use Python’s built-in vars(obj) (which returns obj.__dict__, a dictionary mapping instance attribute names to their current values) alongside pprint.pprint(vars(obj)) for readable formatting—or dir(obj) / inspect.getmembers(obj) when you also need inherited class attributes, methods, and @property descriptors that are not stored in __dict__.
Basic Example
from pprint import pprint
class ServerConfig:
default_timeout = 30 # Class attribute (NOT inside instance __dict__)
def __init__(self, host: str, port: int, debug: bool = False) -> None:
self.host = host
self.port = port
self.debug = debug
cfg = ServerConfig("127.0.0.1", 8080, debug=True)
# 1. Recommended for instance attributes + values (returns dict):
print(vars(cfg))
# Output: {'host': '127.0.0.1', 'port': 8080, 'debug': True}
# 2. Pretty-print large nested attribute dictionaries cleanly:
pprint(vars(cfg))
# 3. Inspect ALL attributes (including inherited methods, class vars, and @property):
print([name for name in dir(cfg) if not name.startswith("__")])
# Output: ['debug', 'default_timeout', 'host', 'port']
Key Details & Edge Cases
vars(obj)raisesTypeErroron objects without__dict__(__slots__, built-inint/str/list,namedtuple):- Classes that define
__slots__(as well as built-in C types like42,"abc", ordatetime.date) do not allocate a per-instance__dict__, so callingvars(obj)raisesTypeError: vars() argument must have __dict__ attribute. - On
__slots__objects, collect attribute-value pairs with{slot: getattr(obj, slot) for slot in obj.__slots__ if hasattr(obj, slot)}.
- Classes that define
vars(obj)shows ONLY instance attributes—NOT class variables, methods, or@propertyvalues:- Because
vars(obj)simply returnsobj.__dict__, class-level attributes (ServerConfig.default_timeout), methods, and computed@propertygetters are omitted. - To inspect all accessible attributes and their evaluated values (including
@propertyand inherited attributes), useinspect.getmembers(obj)(note:inspect.getmembers()executes every@propertygetter on the object, so avoid it if properties trigger network/database side effects).
- Because
- Printing
vars()with no arguments (vars()):- Calling
vars()without an argument acts identically tolocals(), returning a dictionary of all local variables in the current scope.
- Calling
- Security and circular-reference caveat when dumping live objects:
vars(obj)exposes raw internal fields—including private_secretor_passwordattributes—and returns a live reference toobj.__dict__(mutating the returned dict directly mutates the object’s attributes!).
Comparison of Object Inspection Built-ins & Stdlib Functions
| Function | Returns | Shows Values? | Includes Methods, Class Vars & @property? |
Works on __slots__ / Built-ins? |
Best Used When |
|---|---|---|---|---|---|
vars(obj) (Recommended) |
dict[str, Any] (obj.__dict__) |
Yes | No (instance __dict__ only) |
No (raises TypeError) |
Quickly printing or inspecting all instance attributes and their values. |
pprint(vars(obj)) |
Prints formatted dict to stdout |
Yes | No | No | Debugging complex objects with nested lists/dicts cleanly in the terminal. |
dir(obj) |
list[str] (sorted names) |
No (names only) | Yes | Yes | Discovering available method and attribute names on any Python object. |
inspect.getmembers(obj) |
list[tuple[str, Any]] |
Yes (evaluates @property) |
Yes | Yes | Full introspection of both instance/class attributes and bound methods. |
You must log in or register to comment.
