[Python-Dev] bytes & bytearray
pmiscml at gmail.com
Mon Jan 19 20:43:40 CET 2015
On Mon, 19 Jan 2015 08:36:55 -0800
Ethan Furman <ethan at stoneleaf.us> wrote:
> I was checking the documentation  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.
Well, those "operations" come from string methods. String methods
always return a copy, so I'm not sure the same methods, applied to
bytearray *could* reasonably be inplace operations, without surprising
user a lot.
But at the same, a usecase of inplace operations on bytearrays is
valid, and I'd like to take a chance to branch the topic to discuss
how they possibly could be implemented.
> The section just prior to that  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:
Per above, I'd formulate it differently: methods inherited from string
always return a new instance, while some *operators* modify it inplace
(and yes, those are usually the same operators that modify other
So, suppose there's a requirement to support inplace operations
(methods) on bytearray, what would be Pythonic way to implement it?
, or maybe
> bytearray(b'Chapter Title').center()
> bytearray(b' Chapter Title ').replace(b' ', b'- * - ')
> bytearray(b'abc'] = ord(b'z')
> bytearray(b'def'] += b'ghi'
> bytearray(b'123'] *= 3
Paul mailto:pmiscml at gmail.com
More information about the Python-Dev