Reputation: 96
b = bytearray(1)
m = memoryview(b)
Since the type(b[0]) is int, I would expect type(m[0]) to be int also. Starting in Python 3.2 this is true. But in Python 2.7, the type is str. I need to be able to pass a memoryview to functions which expect an array of int.
In Python 2.7, I could create a wrapper class and override __getitem__
. But is there a trick to tell a memoryview object to return int elements?
Upvotes: 4
Views: 1696
Reputation: 59594
Using ord
should do the trick:
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
>>> b = bytearray(1)
>>> m = memoryview(b)
>>> m[0]
'\x00'
>>> ord(m[0])
0
>>> map(ord, m)
[0]
>>>
This is because in Python 2 byte data is stored in strings. Python 3 now distinguishes bytes and strings (unicode).
Upvotes: 1
Reputation: 14999
No, there's no way to cause memoryview
's __getitem__
to return int
objects.
Upvotes: 1