Python vars()

The vars() function returns the __dict__ attribute of the given object if the object has __dict__ attribute.

The syntax of vars() is:


vars() Parameters

The vars() takes maximum of one parameter.

  • object (optional) - can be module, class, instance, or any object having __dict__ attribute.

Return Value from vars()

The vars() returns the __dict__ attribute of the given object. If the object passed to vars() doesn't have __dict__ attribute, it raises a TypeError exception.

Note: __dict__ is a dictionary or a mapping object. It stores object's (writable) attributes.

If no argument is passed to vars(), this function acts like locals() function.

Example: How vars() works?

class Foo:
  def __init__(self, a = 5, b = 10):
    self.a = a
    self.b = b
InstanceOfFoo = Foo()

When you run the program, the output will be:

{'a': 5, 'b': 10}

Also, run these statements on Python shell:

>>> vars(list)
>>> vars(str)
>>> vars(dict)