effectivepython
effectivepython copied to clipboard
Item 47, pages 199 & 200: error in code snippet: `data` param value is never assigned to the protected `_data` attribute
(2nd ed)
What is written
See code snippet at the bottom of the page 199:
(...) For example, say that I want attribute accesses on my object to actually look up keys in an associated dictionary:
class BrokenDictionaryRecord:
def __init__(self, data):
self._data = {}
def __getattribute__(self, name):
print(f'* Called __getattribute__({name!r})')
return self._data[name]
data = BrokenDictionaryRecord({'foo': 3})
data.foo
What is wrong
-
Wrong expression in the code snippet at the bottom of the page 199:
self._data = {}should beself._data = data, otherwise thedataparam value is never assigned to the protected_dataattribute. -
"Cosmetic" typo:
data.foo(the last line) should rather beprint('foo: ', data.foo)for the "broken" code snippet to be as close as possible to its "fixed" counterpart.
Thank you for the report! Yes it should be self.data = data. I removed the print() part of this to reduce the line noise so it's clear that the error is entirely caused by the attribute access, not trying to stringify the object.
Didn't mean to close this :)