What built-in Python function inspects and prints all attributes and values of an object? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

What built-in Python function inspects and prints all attributes and values of an object?

message-square
0

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) raises TypeError on objects without __dict__ (__slots__, built-in int/str/list, namedtuple):
    • Classes that define __slots__ (as well as built-in C types like 42, "abc", or datetime.date) do not allocate a per-instance __dict__, so calling vars(obj) raises TypeError: 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)}.
  • vars(obj) shows ONLY instance attributes—NOT class variables, methods, or @property values:
    • Because vars(obj) simply returns obj.__dict__, class-level attributes (ServerConfig.default_timeout), methods, and computed @property getters are omitted.
    • To inspect all accessible attributes and their evaluated values (including @property and inherited attributes), use inspect.getmembers(obj) (note: inspect.getmembers() executes every @property getter on the object, so avoid it if properties trigger network/database side effects).
  • Printing vars() with no arguments (vars()):
    • Calling vars() without an argument acts identically to locals(), returning a dictionary of all local variables in the current scope.
  • Security and circular-reference caveat when dumping live objects:
    • vars(obj) exposes raw internal fields—including private _secret or _password attributes—and returns a live reference to obj.__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.