[Python-3000] bytes: compare bytes to integer

Barry Warsaw barry at python.org
Tue Aug 14 15:45:45 CEST 2007


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

On Aug 12, 2007, at 1:41 PM, Georg Brandl wrote:

> Bill Janssen schrieb:
>>> I don't like the behaviour of Python 3000 when we compare a bytes  
>>> strings
>>> with length=1:
>>>>>> b'xyz'[0] == b'x'
>>>    False
>>>
>>> The code can be see as:
>>>>>> ord(b'x') == b'x'
>>>    False
>>>
>>> or also:
>>>>>> 120 == b'x'
>>>    False
>>>
>>> Two solutions:
>>>  1. b'xyz'[0] returns a new bytes object (b'x' instead of 120)
>>>     like b'xyz'[0:1] does
>>>  2. allow to compare a bytes string of 1 byte with an integer
>>>
>>> I prefer (2) since (1) is wrong: bytes contains integers and not  
>>> bytes!
>>
>> Why not just write
>>
>>    b'xyz'[0:1] == b'x'
>>
>> in the first place?  Let's not start adding "special" cases.
>
> Hm... I have a feeling that this will be one of the first entries in a
> hypothetical "Python 3.0 Gotchas" list.

Yes, it will because the b-prefix tricks you by being just similar  
enough to 8-bit strings for you to want them to act the same way.   
I'm not advocating getting rid of bytes literals though (they are  
just too handy), but if you were forced to spell it bytes('xyz') I  
don't think you'd get as much confusion.

Any tutorial on bytes should include the following example:

 >>> a = list('xyz')
 >>> a[0]
'x'
 >>> a[0:1]
['x']
 >>> b = bytes('xyz')
 >>> b[0]
120
 >>> b[0:1]
b'x'
 >>> b == b'xyz'
True

That makes it pretty clear, IMO.
- -Barry



-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (Darwin)

iQCVAwUBRsGyC3EjvBPtnXfVAQJEtAQAtMUk8fVAFeMHYam6iNg4G3+NwmPWVXp4
YJSh8ZBEICSNlyJSNk8ntE0vKkqLSFMnI24RtoFDJJ2lKrbPtBoH2OyWuXHgfCzd
VG/LBMjMRV0IMQjkl2EtpD2atBBfDhQ6IPZtqaZJQ7HM10IUZtEq3gf/Q2Alttm4
nr4W46Pny3s=
=1rz/
-----END PGP SIGNATURE-----


More information about the Python-3000 mailing list