The vars()
function returns the __dict__
attribute of an object, which contains its namespace (attributes and values). It’s useful for debugging, dynamic attribute access, and introspection.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(vars(p))
Output:
{'name': 'Alice', 'age': 30}
Returns a dictionary of the object’s attributes.
Syntax
vars(object)
- object (optional) → An instance with a
__dict__
attribute. - Returns → A dictionary of the object’s attributes.
1. Getting an Object’s Attributes as a Dictionary
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
c = Car("Toyota", 2022)
print(vars(c))
# Output: {'brand': 'Toyota', 'year': 2022}
Returns all attributes in a dictionary.
2. Modifying an Object’s Attributes with vars()
person = Person("Bob", 25)
vars(person)["age"] = 26 # Change age directly
print(person.age)
# Output: 26
Lets you modify attributes dynamically.
3. Using vars()
on a Module
import math
print(vars(math)["pi"])
# Output: 3.141592653589793
Accesses module attributes dynamically.
4. Using vars()
Without Arguments (Equivalent to locals()
)
x = 10
y = 20
print(vars())
# Output: {'x': 10, 'y': 20, ...}
Returns all local variables in the current scope.
5. Checking Class Attributes (Not Instance Attributes)
class Sample:
data = "Static Attribute"
print(vars(Sample))
# Output: MappingProxyType({'__module__': '__main__', 'data': 'Static Attribute', ...})
For classes, vars()
returns a mapping proxy, not an editable dictionary.
6. Using vars()
for Dynamic Attribute Handling
class DynamicObject:
pass
obj = DynamicObject()
vars(obj)["new_attr"] = "Hello"
print(obj.new_attr)
# Output: Hello
Dynamically adds new attributes to an object.
7. Using vars()
in Debugging
def debug():
a = 10
b = 20
print(vars()) # Show all local variables
debug()
# Output: {'a': 10, 'b': 20}
Shows all variables in the function scope.
Key Notes
- ✔ Returns an object’s attributes as a dictionary.
- ✔ Works on instances, modules, and scopes.
- ✔ Modifies attributes dynamically.
- ✔ Use
vars()
inside functions to inspect local variables.
By using vars()
, you can inspect objects, modify attributes dynamically, and debug efficiently. 🚀