Python vars

Python vars() builtin function is used to get the __dict__ attribute of the given object.

In this tutorial, we will learn about the syntax of Python vars() function, and learn how to use this function with the help of examples.

Syntax

The syntax of vars() function is

vars([object])

where

Parameter Required/Optional Description
object Required A Python object with a __dict__ attribute.

Returns

The function returns a dictionary.

Examples

1 Get dict attribute for Class

In this example, we define a class, and get the __dict__ attribute of this class.

Python Program

class A:
    name = 'Apple'
    count = 25
    
result = vars(A)
print(result)

Output

{'__module__': '__main__', 'name': 'Apple', 'count': 25, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

2 Get dict attribute for a List

In this example, we try to get the __dict__ attribute of a list object. Since a list does not contain a __dict__ attribute, interpreter would raise TypeError.

Python Program

x = ['apple', 'banana']
result = vars(x)
print(result)

Output

Traceback (most recent call last):
  File "/Users/tutorialkart/Desktop/Projects/PythonTutorial/Example.py", line 2, in <module>
    result = vars(x)
TypeError: vars() argument must have __dict__ attribute

Conclusion

In this Python Tutorial, we have learnt the syntax of Python vars() builtin function, and also learned how to use this function, with the help of Python example programs.