What is vars() in Python?

Overview

The vars() method is a built-in Python function that returns the __dict__ attribute of an object.

Syntax

The syntax for the vars() method is as follows:

vars(object)

Parameters

The vars() method only takes one required parameter, which is an object. The object can be a class, module, instance, etc.

Return value

The return value is the __dict__ attribute. However, if the object does not have any such attribute, the function raises a TypeError.

Example

In the code below, the vars() function returns the key-value pair of the class object in the first case.

Note: When an argument with no __dict__ attribute is passed into the vars() function, the function gives an error.

# dict attribute present
class School:
def __init__(self, section1 = 55, section2 = 73):
self.x = section1
self.y = section2
object = School()
print('Class object:', vars(object))
# dict attribute absent
print('List object', vars([1,2,3]))