vars() Built-in Function


Python - vars()

Python vars() built-in function is used to get the __dict__ attribute of an object if it exists.

vars() built-in function can be used for debugging, dynamic attribute access, or converting objects to dictionaries, etc.

In this tutorial, we will learn the syntax and usage of vars() built-in function, and cover the above said scenarios with examples.

Syntax

The syntax of vars() function is

vars(object)

where

ParameterDescription
objectAny Python object.

Examples

1. Get attributes of an object as dictionary

In the following program, we define a class named Student with two attributes. We create a new object of type Student, and then using vars() built-in function, we shall get the attributes and their values as a dictionary. attribute is the key, and its value if the respective value for the key.

Python Program

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create an object of type Student
student1 = Student("Ram", 12)

# Get attributes of the object as a dictionary
attributes = vars(student1)
print(attributes)

Output

{'name': 'Ram', 'age': 12}

Uses of vars()

vars() built-in function can be used for the following purposes.

  • Debugging: vars() can be used to inspect the state of an object at a certain point in the code. By calling vars() on the object, you can see all of its attributes and their current values. This can be especially helpful when trying to diagnose errors or unexpected behavior in your code.
  • Dynamic attribute access: If you have an object and want to access one of its attributes dynamically, you can use vars() to get the object's namespace and then access the attribute as a dictionary key. For example, vars(my_obj)['my_attribute'] will return the value of the my_attribute attribute of my_obj.
  • Converting objects to dictionaries: Since vars() returns the namespace of an object as a dictionary, it can be used to convert objects to dictionaries. This can be useful when you need to serialize an object or pass its data to another part of your code.

Summary

In this Built-in Functions tutorial, we learned the syntax of the frozenset() built-in function, and how to use this function to create a frozenset object.