Editor

Fix the Recursive __setattr__

Advanced · Fix the bug · from __getattr__ and __setattr__: Dynamic Attribute Access in Python

From the lesson: __getattr__ and __setattr__: Dynamic Attribute Access in Python

Most of the time, Python attributes are straightforward. You set obj.x = 5, and later obj.x gives you 5. But what if you want attributes that don't actually exist - attributes that are computed on the fly, or that trigger side effects when accessed?

Read the lesson

This code tries to log attribute changes, but it crashes with infinite recursion. Fix it so it prints:

Setting name = Alice
Setting age = 30
Alice is 30
class LoggedAttrs:
def __init__(self, name, age):
self.name = name
self.age = age
def __setattr__(self, name, value):
print(f'Setting {name} = {value}')
# Bug: this calls __setattr__ again!
self.name = value
obj = LoggedAttrs('Alice', 30)
print(f'{obj.name} is {obj.age}')

More __getattr__ and __setattr__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz