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

ParameterRequired/OptionalDescription
objectRequiredA Python object with a __dict__ attribute.

Returns

The function returns a dictionary.

Examples

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)
Try Online

Output

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

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)
Try Online

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.