[docs] [issue35119] Customizing module attribute access example raises RecursionError

Ronald Oussoren report at bugs.python.org
Wed Oct 31 11:59:07 EDT 2018


Ronald Oussoren <ronaldoussoren at mac.com> added the comment:

I'm not convinced that any change is needed, this is completely expected behaviour (and not special to modules).

The following code also raises RecursionError:

class VerboseObject:
    def __setattr__(self, nm, value):
        print(f"Setting {nm} to {value}")
        setattr(self, nm, value)

o = VerboseObject()
o.a = 42

This is because setattr() calls the __setattr__ method, which calls setattr() again, ... .


The fix is to call super().__setattr__ instead:

class VerboseObject:
    def __setattr__(self, nm, value):
        print(f"Setting {nm} to {value}")
        super().__setattr__(nm, value)

o = VerboseObject()
o.a = 42

----------
nosy: +ronaldoussoren

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35119>
_______________________________________


More information about the docs mailing list