vars()
The direct pointer to __dict__ — instance-only attributes, declaration order, live view.
Demo
The demo picks a category (module / class / instance) and shows what vars() would return for a representative object. Modules have __dict__ containing their names. User classes have __dict__ containing methods and class attributes. Instances have __dict__ containing per-instance attributes. Built-in types like str do NOT have __dict__ and raise TypeError.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | no | An object with a __dict__ attribute (most user classes, modules, and instances). Without an argument, returns locals(). Built-in types (int, list, str, ...) do NOT have __dict__ and raise TypeError. |
Return value
dict — The __dict__ attribute of the given object. Without an argument, returns the local scope (like locals()). With an object: returns its __dict__ — the instance-specific writable attribute namespace. Not all objects have __dict__ (e.g. built-in types like int, list, str).
Common patterns
print(vars(user)) # {"name": "Alice", "age": 30}
import json json.dumps(vars(obj))
vars(a) == vars(b)
vars(obj)["new_attr"] = value # same as: obj.new_attr = value
Examples
Pitfalls
vars(42)
dir(42)
set(vars(obj)) == set(dir(obj))
vars(obj) # just instance attrs dir(obj) # all accessible names
snapshot = vars(obj) obj.x = 99 snapshot["x"]
snapshot = dict(vars(obj))
class Point: __slots__ = ("x", "y") vars(Point())
{s: getattr(obj, s) for s in obj.__slots__}
When to use
- Inspecting instance state during debugging
- Serializing simple "data bag" objects to JSON or repr
- Iterating over an object's writable attributes
- Building an equality check based on instance state
- Object might not have __dict__ → guard with hasattr(obj, "__dict__")
- You want inherited methods too → dir(obj)
- You want a snapshot → wrap in dict() to copy
- __slots__ classes → attribute-by-attribute access
Notes
FAQ
vars gives you the __dict__ — just the instance-specific writable attributes, in declaration order (Python 3.7+). dir walks the whole MRO to return every accessible name (including inherited methods), sorted alphabetically. Both are useful; they answer different questions.