Skip to content
Tutorials Center
My learning

Topics

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.

Python
class P:
    def __init__(self): self.x, self.y = 1, 2

vars(P())   # {'x': 1, 'y': 2}

Try it

Python Looking inside objects

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.

Python No __dict__, locals and modules

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

Python
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 with dict(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__, no vars(). Built-in types such as int or list, and objects using __slots__ without a __dict__ slot, raise TypeError.
  • Properties and methods live on the class, so they do not appear in vars(instance).
  • vars() without arguments is locals(): 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 have dataclasses.asdict() for the nested case.
  • Custom __dict__. A class may define it differently; vars() simply returns whatever obj.__dict__ is.