Introduction: Python vars() Function
When working with Python, there are situations where you need to inspect the attributes stored inside an object. Whether you’re debugging a program, exploring object data, or working with user-defined classes, manually accessing each attribute can become tedious.
Without a built-in solution, you would need to retrieve every attribute individually, making the code longer and less convenient to maintain.
A simple solution to these situations is the Python vars() Function.
What it is: The vars() function is a built-in Python function that returns the __dict__ attribute of an object as a dictionary. This dictionary contains the object’s writable attributes and their current values. When called without an argument, it behaves like locals() in the current local scope.
Take a look at a quick example to see how it works.
You can also explore its real-world use cases to learn where it is commonly used.
With the basics covered, let’s understand how the vars() function works by exploring its syntax, parameters, return value, and practical examples.
💡 Tip: Learning the vars() function is just one step toward mastering Python’s built-in functions. Visit the
Python Built-in Functions Learning Guide to continue your learning journey.
Syntax, Parameters, Return Value and Examples: Python vars() Function
The following section explains the syntax, parameters, return value, and a quick example of the Python vars() Function.
Syntax
vars(object)
or
vars()
Parameters
| Parameter | Description |
|---|---|
object (optional) |
The object whose attribute dictionary should be returned. If omitted, vars() returns the local symbol table. |
Return Value
| Return Value | Description |
|---|---|
dict |
Returns a dictionary containing the writable attributes of the specified object. Without an argument, it returns the current local symbol table. |
Quick Example
The following example displays the attributes of a simple object.
class Student:
def __init__(self):
self.name = "Alice"
self.age = 20
student = Student()
print(vars(student))
# Output:
{'name': 'Alice', 'age': 20}
The vars() function returns the object’s attributes as a dictionary, where each key represents an attribute name and each value stores the corresponding data.
How the Python vars() Function Works
- The
vars()function returns the writable attributes of an object as a dictionary. - Each dictionary key represents an attribute name.
- Each dictionary value stores the current value of that attribute.
- If called without an argument, it returns the current local symbol table.
- Objects without a
__dict__attribute will raise aTypeError.
Examples: Python vars() Function
The following examples show how the Python vars() Function works in different programming scenarios.
Example 1: Displaying Object Attributes
class Student:
def __init__(self):
self.name = "Alice"
self.age = 20
student = Student()
print(vars(student))
# Output:
{'name': 'Alice', 'age': 20}
Explanation: The vars() function returns a dictionary containing all the writable attributes of the student object along with their current values.
Example 2: Accessing a Specific Attribute
class Employee:
def __init__(self):
self.name = "David"
self.salary = 50000
employee = Employee()
details = vars(employee)
print(details["salary"])
# Output:
50000
Explanation: Since vars() returns a dictionary, individual attributes can be accessed by using their names as dictionary keys.
Example 3: Displaying Attributes After Modification
class Product:
def __init__(self):
self.name = "Laptop"
self.price = 65000
product = Product()
product.price = 62000
print(vars(product))
# Output:
{'name': 'Laptop', 'price': 62000}
Explanation: The dictionary returned by vars() always reflects the object’s current state. Since the price was updated before calling the function, the modified value appears in the output.
Example 4: Using vars() with User Input
class Student:
def __init__(self, name):
self.name = name
student = Student(input("Enter your name: "))
print(vars(student))
# Sample Output:
Enter your name: Emma
{'name': 'Emma'}
Explanation: After receiving the user’s input, the object stores it as an attribute. Calling vars() displays the updated attribute and its value.
Example 5: Comparing vars() and __dict__
class Car:
def __init__(self):
self.brand = "Toyota"
car = Car()
print(vars(car))
print(car.__dict__)
# Output:
{'brand': 'Toyota'}
{'brand': 'Toyota'}
Explanation: Both statements produce the same result because vars() simply returns the object’s __dict__ attribute when it is available.
Example 6: Updating an Attribute Through vars()
class Student:
def __init__(self):
self.name = "Alice"
student = Student()
vars(student)["name"] = "Emma"
print(student.name)
# Output:
Emma
Explanation: Rather than assigning the attribute directly, this example updates it through the dictionary returned by vars(). Since both refer to the same underlying data, the object’s attribute also changes.
Example 7: Handling Objects Without a __dict__ Attribute
number = 100
try:
print(vars(number))
except TypeError as e:
print(e)
# Output:
vars() argument must have __dict__ attribute
Explanation: The vars() function works only with objects that provide a __dict__ attribute. Since integers do not have one, Python raises a TypeError. In this example, the exception is handled using a try-except block so the program continues running.
Use Cases: When to use the vars() Function
Below are some common situations where the Python vars() Function becomes useful:
- Inspecting the attributes of an object.
- Debugging user-defined classes.
- Viewing object data dynamically.
- Updating object attributes through a dictionary.
- Understanding how Python stores object attributes.
- Building debugging and diagnostic utilities.
Key Takeaways: vars() Function
Before wrapping up, here are the key points to remember about the Python vars() Function:
- The
vars()function returns the writable attributes of an object as a dictionary. - It accepts an object as an optional argument.
- Without an argument, it returns the current local symbol table.
- For most user-defined objects, it returns the object’s
__dict__attribute. - Objects without a
__dict__attribute raise aTypeError. - It is widely used for debugging, inspection, and understanding object attributes.
In short, the Python vars() Function provides a convenient way to inspect and work with object attributes, making debugging and object analysis much easier in Python.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.