Python Reference ยท Built-in Functions
Python vars() function
Reference for Python vars(): get an object's __dict__ as a dictionary, differences from dir() and locals(), live-view behavior and objects without __dict__.
The built-in vars() returns the __dict__ attribute of an object: the dictionary that stores its writable attributes. For an instance, that is a name-to-value mapping of its data attributes; for a class or module, it is the namespace of that class or module.
Called with no argument, vars() behaves like locals(). It is handy for debugging, quick serialization of simple objects and passing attributes into formatting calls.
class P: def __init__(self): self.x, self.y = 1, 2 vars(P()) # {'x': 1, 'y': 2}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
vars() vars(object)
| Name | Description |
|---|---|
object |
Any object with a __dict__ attribute: instance, class, module. |
Return value: the object's __dict__ (a dictionary for instances and modules, a read-only mappingproxy for classes); with no argument, the current local namespace.
Raises: TypeError if the object has no __dict__.
Usage notes
- A live view, not a copy, for instances and modules: writing to
vars(obj)changes the object's attributes. Copy it withdict(vars(obj))if you need a snapshot. - Class dictionaries are read-only proxies. Use
setattr()to add class attributes. - Only own data. Inherited attributes and class-level values are not in an instance's
vars();dir()lists inherited names too, but only names, not values. - No
__dict__, novars(). Built-in types such asintorlist, and objects using__slots__without a__dict__slot, raiseTypeError. - Properties and methods live on the class, so they do not appear in
vars(instance). vars()without arguments islocals(): inside a function it returns a snapshot that does not write back, and at module level it is the globals dictionary.- Serialization shortcut.
json.dumps(vars(obj))works for simple objects holding JSON-compatible values; dataclasses havedataclasses.asdict()for the nested case. - Custom
__dict__. A class may define it differently;vars()simply returns whateverobj.__dict__is.