Python vars() Function – Tutorial with Examples

The vars() function in Python is a built-in function that returns the dictionary of an object’s attributes and their values. The function takes an object as an argument and returns a dictionary of the object’s attributes and their values. If the argument passed to the function is not an object, a TypeError is raised.

Syntax

vars(object)

Parameters

  • object : This is the object for which the dictionary of attributes and their values is to be returned.

Return Value

The vars() function returns a dictionary of the object’s attributes and their values. If the argument passed to the function is not an object, a TypeError is raised.

Examples

Example 1: Using vars() with a class object

# using vars() with a class object
class Person:
    name = "John"
    age = 30
p = Person()
print(vars(p))

Output.

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

Example 2: Using vars() with a dictionary

# using vars() with a dictionary
d = {'name': 'John', 'age': 30}
print(vars(d))

Output.

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

Example 3: Using vars() with a built-in type

# using vars() with a built-in type
n = 30
print(vars(n))

Output.

TypeError: vars() argument must have __dict__ attribute

Use Cases

The vars() function is useful in cases where it is necessary to inspect an object’s attributes and their values. For example, it can be used to inspect the state of an object during the development and debugging process, or to inspect the properties of a class at runtime. The function is also useful for working with dynamically created objects, as it allows the user to access and modify the attributes and values of the object on the fly.

In addition, the vars() function can also be used in combination with the setattr() and getattr() functions to dynamically access and modify the attributes and values of an object. This makes it an extremely versatile and powerful tool in a variety of use cases.

It is important to note that the vars() function only works with objects that have a __dict__ attribute. This includes class objects, instances of classes, and dictionaries. Built-in types such as integers, strings, and lists do not have a __dict__ attribute and will raise a TypeError if passed as an argument to the vars() function.

In conclusion, the vars() function is a useful tool for inspecting and manipulating the attributes and values of objects in Python. Whether you are working on a complex project or simply experimenting with different data structures, the vars() function is a powerful tool that can help you understand and manipulate your objects in a more efficient and effective manner.

Leave a Reply

Your email address will not be published. Required fields are marked *