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
| Parameter | Description |
|---|---|
object optional |
A module, class or instance with a __dict__. |
Return value
A dictionary of attributes.
Examples
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]'}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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dir()· List the names an object has, such as attributes and methods. With no argument, list the names in the current scope.locals()· Return a dictionary of the local variables in the current scope. Inside a function it is a snapshot since Python 3.13.getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.setattr()· Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.- Python Classes and Objects · tutorial
- Python Dataclasses · tutorial