Python 3 reference · Built-in Functions

Python vars() Function

Return the __dict__ of a module, class or object: its writable attributes as a dictionary. With no argument, like locals().

Python 3 Since 3.0

Syntax

vars()
vars(object)

Parameters

ParameterDescription
object optional A module, class or instance with a __dict__.

Return value

A dictionary of attributes.

Examples

An object's attributesTry it yourself
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

print(vars(User("Ada", "[email protected]")))

Output

{'name': 'Ada', 'email': '[email protected]'}
Convert an object to a dictTry it yourself
from types import SimpleNamespace
settings = SimpleNamespace(theme="dark", lang="en")
print(vars(settings))
print(dict(vars(settings), lang="fr"))

Output

{'theme': 'dark', 'lang': 'en'}
{'theme': 'dark', 'lang': 'fr'}

Good to know

Objects that use __slots__ (and many built-in types) have no __dict__, so vars() raises TypeError for them. For data classes, dataclasses.asdict() is often what you want.

Version history

VersionChange
Python 3.0Added