vars() function in Python

vars() function belongs to the collection of inbuilt functions provided by the Python standard library. It returns the __dic__ attribute of an associated object to the console.



Return Type

<Dictionary Type>


vars() function accepts only one parameter. It takes an object as its parameter which can be any module, class or any object having __dict__ attribute associated with it.

This parameter is optional in nature. In case the function is used without parameters A dictionary containing local symbol table is displayed.

Exceptions Involved

If the argument passed doesn’t match the attribute, it raises the TypeError exception.


Vars() acts like locals() method when no argument is passed.The locals() method modifies and returns-back a dictionary of the currently present local symbol table.

Working Mechanism

The <class−name> associates with the __name__ attribute; the bases tuple get itemized with the base classes and associates the __bases__ attribute & dictionary is the current namespace that contains definitions contained in class body and gets copied to a standard dictionary type to display as the __dict__ attribute.

Let’s us discuss some examples so that we can grasp the concept of vars() function


 Live Demo

class test:
   def __init__(self, integer_1=555, integer_2=787):
      self.integer_1 = integer_1
      self.integer_2 = integer_2
   obj_test = test()


{'integer_1': 555, 'integer_2': 787}


 Live Demo

class sample:
   company = "Tutorial's Point "
   Number = 4
   Topic = "Python 3.x."
obj = vars(sample)


{'__doc__': None, '__weakref__': <attribute '__weakref__' of 'sample' objects>, 'Topic': 'Python 3.x.', 'company': "Tutorial's Point ", '__module__': '__main__', 'Number': 4, '__dict__': <attribute '__dict__' of 'sample' objects>}


 Live Demo

class test():
# Python __repr__() function returns the representation of the object.
# It may contain any valid expression such as tuples, list, dictionary, string, set etc
   def __repr__(self):
      return "Tutorial's point"
   def localvariables(self):
      number = 4
      return locals()

if __name__ == "__main__":
   obj = test()
   print (obj.localvariables())


{'self': Tutorial's point, 'number': 4}


First example code depicts the use of __dict__ attributes associated with the constructor of the class with the default value set in the constructor method.4

Second example code depicts the use of __dict__ attributes associated with the class itself with the __doc__ attribute empty.

Third example code depicts the use of __dict__ attributes associated with a user-defined function inside the class with the variable in the local scope.


In this article, we learnt how to implement vars function in various cases in Python 3.x. Or earlier. You can implement the same algorithm to use the vars function whenever needed.