The vars() is a built-in function in Python that returns the dictionary representation (__dict__) for a module, a class, an instance, or any other object.

Python vars Function:

An object such as modules and instances have  __dict__ attribute that can be updated, while other objects have to write restrictions. However, if an object doesn’t have a dict attribute then it will raise a TypeError exception.

Method signature

The signature for the vars() function is as shown below. An object is optional.

vars(object)

Method parameters and return type

  • This function has one optional parameter object. Here, an object can be a module, a class, an instance, or any other object that supports __dict__ attribute.
  • However, it returns the __dict__ attribute for a module, a class, an instance, or any other object.

Python Built-in Function vars Examples:

Example 1:  For this example, let us demonstrate the working of the vars function with a class and an instance.

#Defining class
class Student:
    def __init__(self, n, a):
        self.name=n
        self.age=a
#Creating instance
s=Student("John",21)
#Using vars and Printing
print(vars(s))

Output

{'name': 'John', 'age': 21}

Example 2: In this case, we will demonstrate the use of vars without parameters. Hence it acts as the locals() function.

#Defining Class
class Student:
    def __init__(self, n, a):
        self.name=n
        self.age=a
		#Using vars()
        print(vars())
s=Student("John",21)

Output

{'self': <__main__.Student object at 0x7f53e2f92ee0>, 'n': 'John', 'a': 21}

Example 3: For this example, we will take a string and a list as a parameter. Just because, both of them don’t have a dict attribute, it will raise an exception.

#Initializing
s="Python"
l=[1,2,3,4]
#using vars and printing
print("string",vars(s),"list",vars(l))

Output

Traceback (most recent call last):
  File "main.py", line 3, in 
    print("string",vars(s),"list",vars(l))
TypeError: vars() argument must have __dict__ attribute

Conclusion

The vars() function returns the dict attribute of an object passed as a parameter. However, if the parameter object doesn’t have a dict attribute, it will raise an exception.

References

Happy Learning 🙂

Leave A Comment