bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.2k stars 710 forks source link

Item 47, pages 199 & 200: error in code snippet: `data` param value is never assigned to the protected `_data` attribute #115

Open kirisakow opened 1 year ago

kirisakow commented 1 year ago

(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 be `self._data = data`, otherwise the `data` param value is never assigned to the protected `_data` attribute.

* "Cosmetic" typo: `data.foo` (the last line) should rather be `print('foo: ', data.foo)` for the "broken" code snippet to be as close as possible to its "fixed" counterpart.
bslatkin commented 1 month ago

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.

bslatkin commented 1 month ago

Didn't mean to close this :)