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 thevars()function, the function gives an error.
# dict attribute presentclass School:def __init__(self, section1 = 55, section2 = 73):self.x = section1self.y = section2object = School()print('Class object:', vars(object))# dict attribute absentprint('List object', vars([1,2,3]))