[Python-Dev] Binary concatenation (was Re: (no subject))
Nick Coghlan
ncoghlan at gmail.com
Wed Feb 11 07:12:40 CET 2015
On 11 February 2015 at 15:45, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Antoine Pitrou wrote:
>>>>>
>>>>> bytearray(b"a") + b"bc"
>>
>>
>> bytearray(b'abc')
>>
>>>>> b"a" + bytearray(b"bc")
>>
>>
>> b'abc'
>>
>> It's quite convenient.
>
>
> It's a bit disconcerting that the left operand wins,
> rather than one of them being designated as the
> "wider" type, as occurs with many other operations on
> mixed types, e.g. int + float.
>
> In any case, these seem to be special-case combinations.
> It's not so promiscuous as to accept any old iterable
> on the right:
Binary concatenation accepts any bytes-like object (aka buffer API
implementing type), and it's the fact that both bytes and bytearray
interoperate with any bytes-like object that results in the "left
operand wins" behaviour when you use them together.
I don't believe we deliberately designed it that way, it's just an
inherent consequence of having both types implement concatenation
based on the buffer protocol rather than using any kind of type check.
If we *had* tried to define one of the two as encompassing the other,
then we would have also run into http://bugs.python.org/issue11477
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev
mailing list