vars() is a built-in Python function that returns the __dict__ attribute of an object — a dictionary containing all its writable attributes (instance variables) and their values. It’s the go-to tool for runtime inspection and manipulation of an object’s state, especially useful for dynamic attribute access, debugging, serialization, and metaprogramming. In 2026, vars() remains essential in data science (inspecting pandas/Polars/Dask objects, dynamic config), software engineering (object serialization, plugin systems), and interactive environments (Jupyter, IPython) — providing a live, mutable view into an object’s namespace when it has a __dict__ (most custom classes do).
Here’s a complete, practical guide to using vars() in Python: basic inspection & modification, real-world patterns (earthquake event introspection, dynamic attribute enrichment, serialization), and modern best practices with type hints, safety, performance, and integration with dataclasses/Pydantic/Polars/Dask/pandas.
Basic vars(obj) — returns the object’s attribute dictionary (or module globals if no arg).
class Earthquake:
def __init__(self, mag, place):
self.mag = mag
self.place = place
self._internal = "hidden"
eq = Earthquake(7.2, "Japan")
print(vars(eq))
# {'mag': 7.2, 'place': 'Japan', '_internal': 'hidden'}
# Modify via vars()
vars(eq)['mag'] = 8.1
print(eq.mag) # 8.1 (changed!)
# Add new attribute dynamically
vars(eq)['depth'] = 25.0
print(eq.depth) # 25.0
vars() without arguments — returns current local namespace (like locals()).
def process_quake(mag, place):
depth = 25.0
is_strong = mag >= 7.0
local_state = vars()
print("Local vars:", local_state)
# {'mag': 7.2, 'place': 'Japan', 'depth': 25.0, 'is_strong': True}
# Modify local variable via vars()
local_state['depth'] = 30.0
print(depth) # 30.0 (changed in CPython, but implementation-dependent)
process_quake(7.2, "Japan")
Real-world pattern: earthquake event introspection & dynamic serialization — use vars() for attribute access and export.
@dataclass
class QuakeEvent:
mag: float
place: str
depth: float = 0.0
time: str = "unknown"
event = QuakeEvent(7.5, "Alaska", 10.0, "2025-03-01")
# Inspect all attributes
print(vars(event))
# {'mag': 7.5, 'place': 'Alaska', 'depth': 10.0, 'time': '2025-03-01'}
# Dynamic export to dict (simple serialization)
event_dict = vars(event).copy()
event_dict['energy'] = 10 ** (1.5 * event.mag + 4.8) # add computed field
print(event_dict)
# Batch attribute update from config
updates = {'mag': 8.0, 'place': 'Chile'}
vars(event).update(updates)
print(vars(event)) # updated attributes
# Polars/Dask: convert DataFrame row to dict via vars-like
row_dict = dict(df.iloc[0]) # pandas row to dict
print(row_dict)
Best practices for vars() in Python & data workflows. Prefer vars(obj) — when you need a dict of attributes; use obj.__dict__ directly for same result (faster). Modern tip: use Polars df.row(0, named=True) — row to dict; Dask for distributed inspection. Use vars() for debugging — print(vars(obj)) to see state. Add type hints — def inspect_obj(obj: Any) -> dict[str, Any]: return vars(obj). Avoid modifying vars() — updates may not affect object in some cases (implementation detail). Use vars() with dataclasses.asdict() — for safer, complete export. Use vars() in serialization — json.dumps(vars(obj)) (simple objects). Use vars() in testing — assert vars(obj)['mag'] == expected. Use vars() in decorators — inspect wrapped function locals. Use vars() with setattr() — dynamic attribute setting. Use vars(obj).update({...}) — batch update (if obj has __dict__). Use vars() with types.SimpleNamespace — dynamic objects: ns = SimpleNamespace(); vars(ns).update({...}). Use vars() in metaclasses — inspect class __dict__. Use vars(module) — module globals (like globals()). Use vars() in class bodies — shows class attributes. Use vars() with pprint.pprint(vars(obj)) — pretty-print for large objects. Use vars() in error handling — raise ValueError(f"Missing attr: {vars(obj).keys()}"). Use vars() with inspect.getmembers(obj) — more complete inspection (includes methods). Use vars() in logging — logger.debug(vars(obj)).
vars([obj]) returns the __dict__ of an object (or local/module globals if no arg) — inspect, modify, or export attributes as a dictionary. In 2026, use for debugging, dynamic attribute handling, serialization, and integrate with dataclasses/Pydantic/Polars/Dask for object state access. Master vars(), and you’ll gain powerful runtime introspection and manipulation of object state in any Python project.
Next time you need to see or change an object’s attributes as a dict — use vars(). It’s Python’s cleanest way to say: “Give me the internal dictionary of this object — inspect or update at will.”