vars() Function in Python

Python vars() Function

In Python, the vars() function is a built-in function that returns the __dict__ attribute of an object. The __dict__ attribute is a dictionary that contains the namespace of the object, which includes its attributes and their values. Essentially, vars() allows you to access the dictionary of instance variables and their values for an object, and it is particularly useful for objects created from user-defined classes.

Here's the syntax of the vars() function:

vars([object])

Parameters:

  • object (optional): The object for which you want to retrieve the namespace. If not provided, the function returns the local namespace as a dictionary.

Usage:

With a Class:

When you use vars() with a class instance, it will return the instance's namespace (attribute-value dictionary):

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(10, 20)
print(vars(obj))  # Output: {'x': 10, 'y': 20}

Without an Object:

When you use vars() without an object, it returns the local namespace as a dictionary:

a = 42
b = "Hello"
print(vars())  # Output: {'a': 42, 'b': 'Hello'}

It's important to note that vars() is primarily used for debugging and introspection purposes. Directly accessing the __dict__ attribute is discouraged in production code, and it's generally better to use proper encapsulation and getters/setters for accessing object attributes.