[Python-Dev] bytes & bytearray

Paul Sokolovsky pmiscml at gmail.com
Mon Jan 19 20:43:40 CET 2015


Hello,

On Mon, 19 Jan 2015 08:36:55 -0800
Ethan Furman <ethan at stoneleaf.us> wrote:

> 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.

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 [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:

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
containers inplace).

So, suppose there's a requirement to support inplace operations
(methods) on bytearray, what would be Pythonic way to implement it?

Something like:

b.lower_inplace()
b.lower_i()

, or maybe

import bytearray_ops
bytearray_ops.lower(b)

?

> New:
> 
>   bytearray(b'Chapter Title').center()
>   bytearray(b' Chapter Title ').replace(b' ', b'- * - ')
> 
> In-place:
> 
>   bytearray(b'abc'][1] = ord(b'z')
>   bytearray(b'def'] += b'ghi'
>   bytearray(b'123'] *= 3


-- 
Best regards,
 Paul                          mailto:pmiscml at gmail.com


More information about the Python-Dev mailing list