Python vars() built-in function

From the Python 3 documentation

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Introduction

The vars() function returns the __dict__ attribute of an object. This dictionary contains the object’s writable attributes. It’s a convenient way to see all the attributes of an object at once.

If called with no argument, vars() acts like locals(), returning a dictionary of the local symbol table.

Examples

Getting the attributes of an object:

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

my_person = Person("Dwight", 35)
print(vars(my_person))
# Output: {'name': 'Dwight', 'age': 35}

Using vars() with no arguments:

def my_function():
    x = 10
    print(vars())

my_function() # Output: {'x': 10}

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.