example-code icon indicating copy to clipboard operation
example-code copied to clipboard

Example 2-21 in book errors out in python 2.7

Open robynsmith opened this issue 9 years ago • 2 comments

# Example 2-21. Changing the value of an array item by poking one of its bytes
import array
numbers = array.array('h', [-2, -1, 0, 1, 2])
memv = memoryview(numbers)

Gives me this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-f1be3db9ba34> in <module>()
----> 1 memv = memoryview(numbers)

TypeError: cannot make memory view because object does not have the buffer interface

Based on research I did, this is a known limitation of python 2.7:

An array can only expose its contents via the old-style buffer interface. This limitation does not apply to Python 3, where memoryview objects can be constructed from arrays, too. Array elements may be multi-byte values.

Source: Python Docs

This info might be useful to someone out there. Not sure if it's worth noting in a future revision of the book :)

robynsmith avatar Jul 23 '17 14:07 robynsmith

Thank you very much for this contribution, @robynsmith . Fluent Python is focused on Python 3. There are many code examples that will not work in Python 2.7. I do point out some of the differences, but it was never my goal to cover all the differences between Python 2 and Python 3.

ramalho avatar Jan 22 '19 19:01 ramalho

Makes sense to me. At this point, this ticket might help someone running into the same issue :P

Thanks for the response! :)

robynsmith avatar Feb 26 '19 14:02 robynsmith