[Python-Dev] Why does _pyio.*.readinto have to work with 'b' arrays?

Nikolaus Rath Nikolaus at rath.org
Sun Jun 15 06:57:12 CEST 2014


On 06/14/2014 09:31 PM, Nick Coghlan wrote:
> On 15 June 2014 10:41, Benjamin Peterson <benjamin at python.org> wrote:
>> On Sat, Jun 14, 2014, at 15:39, Nikolaus Rath wrote:
>>> It seems to me that a much cleaner solution would be to simply declare
>>> _pyio's readinto to only work with bytearrays, and to explicitly raise a
>>> (more helpful) TypeError if anything else is passed in.
>>
>> That seems reasonable. I don't think _pyio's behavior is terribly
>> important compared to the C _io module.
> 
> _pyio was written before the various memoryview fixes that were
> implemented in Python 3.3 - it seems to me it would make more sense to
> use memoryview to correctly handle arbitrary buffer exporters (we
> implemented similar fixes for the base64 module in 3.4).

Definitely. But is there a way to do that without writing C code?

My attempts failed:

>>> from array import array
>>> a = array('b', b'x'*10)
>>> am = memoryview(a)
>>> am[:3] = b'foo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different
structures
>>> am[:3] = memoryview(b'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different
structures
>>> am.format = 'B'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: attribute 'format' of 'memoryview' objects is not writable

The only thing that works is:

>>> am[:3] = array('b', b'foo')

but that's again specific to a being a 'b'-array.


Best,
-Nikolaus

-- 
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F

             »Time flies like an arrow, fruit flies like a Banana.«


More information about the Python-Dev mailing list