Python () Function
The vars() function returns the __dict__ attribute of an object, i.e. a dictionary containing the object's changeable attributes.
Syntax
vars(object)
vars() Parameters
Python vars() function parameters:
| Parameter | Condition | Description |
|---|---|---|
object | Optional | The object whose __dict__ attribute is to be returned |
vars() Return Value
Python vars() function returns:
__dict__attribute of the given object.- dictionary of the current local scope if no object is specified.
TypeError is raised if the object passed does not have the __dict__ attribute.
Examples
Example 1: Using vars() without an Argument
When called without arguments, vars() returns a dictionary containing the local symbol table, which can be useful for introspection of the current local scope.
# vars() with no argument
print(vars())
output
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
Example 2: Using vars() with a Class Instance
For example, consider the following Person class:
class Person:
def __init__(self, name="Tom", age=25, sex="Male"):
self.name = name
self.age = age
self.sex = sex
person = Person()
print(vars(person))
output
{'name': 'Tom', 'age': 25, 'sex': 'Male'}
Observe that vars(person) returns the __dict__ attribute of the Person instance, which is a dictionary containing the attributes name, age, and sex along with their values.
Example 3: Using vars() with Local Variables
The vars() function can be used within a function to introspect local variables and their values.
In the following example, the output includes the local variables a, b and result, showing the dynamic nature of vars().
def calculate_sum(a, b):
result = a + b
variables = vars()
return variables
sum_variables = calculate_sum(5, 7)
print(sum_variables)
output
{'a': 5, 'b': 7, 'result': 12}
Example 4: vars() with Objects Without __dict__ Attribute
Attempting to use vars() function with objects that do not have a __dict__ attribute will result in a TypeError!
For example, strings and numbers do not have __dict__ attribute.
string = "Tom"
print(vars(string)) # raise a TypeError
output
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(vars(string)) # raise a TypeError
TypeError: vars() argument must have __dict__ attribute
number = 132
print(vars(number)) # raise a TypeError
output
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(vars(number)) # raise a TypeError
TypeError: vars() argument must have __dict__ attribute