Python Strinh Immutability Broken!
tjreedy at udel.edu
Wed Aug 27 04:25:04 CEST 2008
Hendrik van Rooyen wrote:
> Terry Reedy:
>> Which essentially is the bytearray type of 3.0.
> How does it differ from plain old array.array(b,”The quick brown fox”)?
The typecode must be quoted as 'b'.
In 3.0, strings become unicode, so an added b prefix is needed.
>>> import array
>>> a = array.array('b', b'fox')
As to your question: the underlying implementation of bytearrays is
based on that of array('b')s. Bytearrays are built in so no import is
needed. Dir() shows that both have all sequence methods, but arrays
also have list methods, while bytearrays also have string/bytes methods.
They have different representations
array('b', [102, 111, 120])
Bytearrays, like lists/arrays, have the __setitem__ method needed to
make them mutable via indexing.
array('b', [98, 111, 120])
Arrays can extend bytearrays but not vice versa. This may be a glitch.
>>> c = a + b
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c = a + b
TypeError: can only append array (not "bytearray") to array
>>> c = b + a
Either can initialize the other
>>> d = array.array('b',c)
array('b', [98, 111, 120, 98, 111, 120])
So if one does more that the common mutable sequence operations, there
is a basis for choosing one or the other.
Terry Jan Reedy
More information about the Python-list