effectivepython icon indicating copy to clipboard operation
effectivepython copied to clipboard

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

Open kirisakow opened this issue 3 years ago • 2 comments

(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.

kirisakow avatar Nov 25 '22 10:11 kirisakow

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 avatar May 31 '24 23:05 bslatkin

Didn't mean to close this :)

bslatkin avatar Jun 01 '24 05:06 bslatkin