[issue8990] array constructor and array.fromstring should accept bytearray.
Terry J. Reedy
report at bugs.python.org
Sat Jun 19 03:05:27 CEST 2010
Terry J. Reedy <tjreedy at udel.edu> added the comment:
Summary: real bug, needs test, patch provided, looks plausible but I am not qualified to even read-review it, let alone apply and test.
(I am removing 3.3 because that is only listed for syntax feature requests that cannot go into 3.2 because of its moratorium on such.)
I agree that this is a bug. For 3.1, the '8.6. array' doc says
"class array.array(typecode[, initializer])
A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, object supporting the buffer interface, or iterable over elements of the appropriate type."
I believe bytearray 'supports the buffer interface', whatever that means in 3.x. 'Readonly' is definitely *not* specified. Even if bytearray did not qualify on that, instances are *definitely* iterable.
The doc goes on: "If given a list or string, the initializer is passed to the new array’s fromlist(), fromstring(), or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method."
For 3.x, this is pretty bad as it is copied without change from 2.x and uses 'string' in the 2.x sense. It seems to me that fromstring/fromunicode should have been renamed to frombytes/fromstring with a 2to3 fixer. Too late now, I suppose. However, if indeed 'fromstring' is intended to mean 'from bytes only and not bytearrays', then bytearrays should be passed on to .extend, which accepts them as well as anything else.
>>> from array import array
array('h', [120, 106, 120, 106, 120])
The two possible fixes:
1. Extend .fromstring to accept bytearrays. Its current doc "Appends items from the string, interpreting the string as an array of machine values " to me supports doing that. This is what Thomas's patch does.
2. If that is rejected, then bytearray initializers should be passed to .extend.
Thomas: a complete patch needs to include a update to the array unit test suite. This can then move to the patch review stage.
stage: -> unit test needed
versions: -Python 3.3
Python tracker <report at bugs.python.org>
More information about the Python-bugs-list