Adding custom attributes in Python - Time & Space Complexity
When we add custom attributes to objects, it is important to know how the time to do this grows as we add more attributes.
We want to understand how the work changes when the number of attributes increases.
Analyze the time complexity of the following code snippet.
class MyObject:
pass
obj = MyObject()
for i in range(n):
setattr(obj, f'attr{i}', i)
This code adds n custom attributes to an object one by one using a loop.
- Primary operation: Adding one attribute to the object using
setattr. - How many times: This operation repeats
ntimes, once for each attribute.
Each new attribute is added one after another, so the total work grows as we add more attributes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 attribute additions |
| 100 | 100 attribute additions |
| 1000 | 1000 attribute additions |
Pattern observation: The work grows directly in proportion to the number of attributes added.
Time Complexity: O(n)
This means the time to add attributes grows linearly with the number of attributes you add.
[X] Wrong: "Adding many attributes is always instant and does not depend on how many there are."
[OK] Correct: Each attribute addition takes some time, so more attributes mean more total time.
Understanding how adding properties to objects scales helps you reason about performance in real programs where objects grow dynamically.
"What if we added all attributes at once using a dictionary update instead of one by one? How would the time complexity change?"