[Python-Dev] bytes & bytearray

Eric V. Smith eric at trueblade.com
Mon Jan 19 18:01:36 CET 2015


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 1/19/2015 11:36 AM, Ethan Furman 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.
> 
> 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:
> 
> 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
> 
> 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.
> 
> Thoughts?

I'd return a new copy (or, not implement it at all and let the default
machinery call __mod__, and do the assignment). That's the least
surprising to me, since the goal is to be compatible with 2.7's str
%-formatting.

- -- 
Eric.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQEcBAEBAgAGBQJUvThwAAoJENxauZFcKtNx/noIAIfIW2Ir4P9bQ9s7bdyJCvMj
RlqfBhWVOjWZ52gK/CdTvpZZDlDUf+gh1JkbvggNvIQHUTy0IY9IxryWvNemfSce
nzZxUhNKzx77f/oGTeGgqBBMZGvCsRCqYFbLBME5LDweiHAIL2MVGqF/SwkobrGq
ruJjSBtNAl28IgpDj7kM7tT7/iXINk6XkVatNa2OxV2FOyYiIz+7Vs2HGpkltzhW
g4qqGEvEpLOl1oRtmI/A3TDFjQgyHc1MKVax6PH/Nq2OMfnoS4hg+jTAzE6Eairh
SmWyZUMjpTeHpCmUgx03WLh8iRTokfE2LN2KJuBN18iAT5EqC6sNTKZm9HX5odw=
=D9zy
-----END PGP SIGNATURE-----


More information about the Python-Dev mailing list