In Python, the vars() function returns a dictionary containing an object's attributes and their values.

Function Syntax

vars([object])

The parameter object is optional. If specified, it returns a dictionary containing the object's attributes and their values, essentially returning the object's __dict__ attribute. If no parameter is specified, it returns a dictionary of local variables and their values in the current scope.

Examples of the vars() Function

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

cls = MyClass()

print(vars(cls))    # {'x': 10, 'y': 20}
print(cls.__dict__) # {'x': 10, 'y': 20}

It essentially returns the object's __dict__ attribute:

class MyClass:
    # Custom __dict__
    __dict__ = {'a','b'}

    def __init__(self):
        self.x = 10
        self.y = 20

cls = MyClass()

print(vars(cls))    # {'a', 'b'}

Without parameters, returns variables in the current scope:

def func():
    x = 123
    print(vars()) # {'x': 123}

a = 1
b = 2

print(vars()) # {'__name__': ... , 'a': 1, 'b': 2}
func()