fluentpython / example-code

Example code for the book Fluent Python, 1st Edition (O'Reilly, 2015)
http://bit.ly/fluentpy
MIT License
5.56k stars 2.18k forks source link

Example 2-21 in book errors out in python 2.7 #11

Closed robynsmith closed 5 years ago

robynsmith commented 7 years ago
# 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 :)

ramalho commented 5 years ago

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.

robynsmith commented 5 years ago

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

Thanks for the response! :)