[Python-Dev] bytes & bytearray

Ethan Furman ethan at stoneleaf.us
Mon Jan 19 17:36:55 CET 2015

I was checking the documentation [1] to see where to put the new information about bytes and bytearray %-formatting, and
noticed that /every/ operation that could modify a bytearray object in place (e.g. center, capitalize, strip, etc.)
instead returns a new copy.

The section just prior to that [2] does say, "As bytearray objects are mutable, they support the mutable sequence
operations ...".

So it seems that when bytearray is treated as ascii data a new bytearry is returned, and when bytearray is treated as a
container it is modified in place:


  bytearray(b'Chapter Title').center()
  bytearray(b' Chapter Title ').replace(b' ', b'- * - ')


  bytearray(b'abc'][1] = ord(b'z')
  bytearray(b'def'] += b'ghi'
  bytearray(b'123'] *= 3

I now have a minor dilemma:  %-formatting is an ascii operation, but it also has an in-place operator (%=) . . . so does
%= modify the bytearray in place just like += and *= do, or does it return a new bytearray just like all the named ascii
operations do?  I do not know which is more surprising: having one of the in-place operators not work in place, or
having an unnamed ascii-operation not return a new copy.



[1] https://docs.python.org/3/library/stdtypes.html#bytes-and-bytearray-operations
[2] https://docs.python.org/3/library/stdtypes.html#bytearray-objects

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150119/9a7be275/attachment.sig>

More information about the Python-Dev mailing list