Iterate over object attributes in python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python provides several ways to iterate over an object's attributes: vars() returns an object's __dict__ (instance attributes only), dir() returns all attributes including inherited ones, inspect.getmembers() gives attribute name-value pairs with filtering, and __dict__ can be accessed directly. The right choice depends on whether you need instance attributes only, class attributes, methods, or everything.
vars() — Instance Attributes
vars(obj) returns the object's __dict__, which contains only instance attributes:
vars() does not include class-level attributes, methods, or properties — only what is assigned to self in __init__ (or later).
dict — Direct Access
Equivalent to vars(), accessing __dict__ directly:
__dict__ and vars() return the same dictionary. vars() is preferred because it is more readable and works with built-in types like modules.
dir() — All Attributes Including Inherited
dir(obj) returns a list of all attribute names, including inherited methods and dunder attributes:
dir() returns names only (no values). To get values, use getattr():
inspect.getmembers() — Filtered Iteration
The inspect module provides getmembers() with optional predicates:
Predicates like inspect.ismethod, inspect.isfunction, and inspect.isclass let you filter precisely.
Filtering Attributes by Type
Serialization Use Case
A common reason to iterate attributes is to serialize an object:
For production serialization, use dataclasses or pydantic:
slots Classes
Classes using __slots__ do not have __dict__:
Common Pitfalls
- Using
vars()on__slots__objects: Classes with__slots__have no__dict__, sovars()raisesTypeError. Iterate overobj.__slots__withgetattr()instead. - Modifying
__dict__during iteration: Changing attributes (adding or deleting) while iterating overvars(obj).items()can causeRuntimeError. Iterate over a copy:list(vars(obj).items()). - Expecting
vars()to include class attributes:vars(obj)only returns instance attributes. Class attributes (defined outside__init__) and inherited attributes are excluded. Usedir()to see everything. - Including methods when you want data only:
dir()andgetattr()return methods alongside data attributes. Filter withnot callable(getattr(obj, attr))to exclude methods. - Properties executing during iteration: Accessing a
@propertyviagetattr()triggers the getter, which may have side effects or raise exceptions. Useinspect.getmembers_static()(Python 3.11+) or check the class descriptor to identify properties before accessing them.
Summary
- Use
vars(obj)orobj.__dict__for instance attributes as a dictionary - Use
dir(obj)for all attribute names including inherited ones and methods - Use
inspect.getmembers(obj, predicate)for filtered name-value pairs - Use
getattr(obj, name)to get the value of an attribute by name fromdir()results - For
__slots__classes, iterate overobj.__slots__since__dict__does not exist - Use
dataclasses.asdict()for clean serialization instead of manual attribute iteration
Related reading
- Iterating each character in a string using Python
- Iterating over dictionaries using 'for' loops
- Iterating over every two elements in a list
- Iterating over tf.Tensor is not allowed AutoGraph is disabled in this function
- Iterating through a range of dates in Python
- Iterating through directories with Python
- Java Virtual Machine vs. Python Interpreter parlance?
- Java Virtual Machine vs. Python Interpreter parlance?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.