vars
Get the dictionary of the attributes of an object.
Python 3.13
vars([object])Parameters
- objectAnyoptional
- An object, module or class; without it, the variables of the current scope.
Return value
A dictionary {attribute name: value}.
Examples
Attributes of an object
Python 3.13
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
print(vars(Point(1, 2))){'x': 1, 'y': 2}Setting attributes through the dictionary
Python 3.13
class Settings:
pass
settings = Settings()
vars(settings).update({'debug': True, 'level': 2})
print(settings.debug, settings.level)True 2
Details
For a regular object, it returns the __dict__ dictionary itself, not a copy, so changing it changes the attributes. Unlike dir, it shows only the object’s own attributes, without class methods. Raises TypeError for numbers, strings and other objects without __dict__.
