Inspect an object’s attribute dictionary using vars().
What You Will Learn
vars(instance) generally returns instance.__dict__; vars() with no argument returns the current local namespace mapping. Slotted objects without __dict__ can raise TypeError for vars(instance).
Dataclasses.fields() is often better for declared fields of a dataclass.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
product = Product("Pen", 3)
print(vars(product))
How the Example Works
- The class Product groups data and behavior; its methods run when called on an instance.
- The variable product holds the result of Product('Pen', 3). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression vars(product) prints {'name': 'Pen', 'price': 3}. Compare that result with the rule above before you change the argument.
Expected output from the example:
{'name': 'Pen', 'price': 3}
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
class Note:
pass
item = Note()
item.text = "Remember"
print(vars(item))
Expected output:
{'text': 'Remember'}
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Inspect a simple instance after adding a new attribute.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming vars() works on every slotted object without a __dict__.
- Modifying the returned dictionary without recognizing it may be live object state.
Key Takeaways
- Inspect an object’s attribute dictionary using vars().
- vars(instance) generally returns instance.__dict__; vars() with no argument returns the current local namespace mapping.
- Dataclasses.fields() is often better for declared fields of a dataclass.