Object introspection
Inspecting an object's stored attributes during debugging or introspection.
Python · Function
vars() returns an object's __dict__ mapping, or behaves like locals() when called without an argument. It raises TypeError for an object that lacks __dict__.
Call vars() with an object to obtain that object's __dict__ mapping. With no argument, it behaves like locals(); an object without __dict__, including an instance of a class using __slots__, causes TypeError.
vars(*object*, /*)| Name | Type | Description |
|---|---|---|
object | object, optional | The object whose __dict__ attribute is returned; omit it to use locals()-equivalent behavior. |
The specified object's __dict__, or the current local namespace when called without an argument.
class User:
role = "admin"
user = User()
attributes = vars(user)
print(attributes)
print(vars(User)["role"])
Shows the instance dictionary and the class dictionary returned by vars().
Inspecting an object's stored attributes during debugging or introspection.
Reading class or instance namespace entries dynamically.
Examining local names in a context where locals()-equivalent behavior is useful.
vars(obj) returns obj.__dict__ when that attribute exists. It works for modules, classes, instances, and other objects exposing a __dict__.
Follow-up: What happens for a slotted instance? It raises TypeError because the instance does not provide __dict__.
Calling vars() without an argument has the same behavior as locals(). The no-argument result follows the documented locals() semantics.
Follow-up: How does this differ from vars(obj)? vars(obj) requires the target object's __dict__, while vars() examines the current local namespace.
vars() does not create a general-purpose attribute dictionary for every object. If the supplied object lacks __dict__, Python raises TypeError.
Follow-up: Why might modifying the returned mapping fail? Some objects impose write restrictions, and class dictionaries are exposed through a mapping proxy.
locals()__dict__types.MappingProxyType