"Byte" type?
Steve Holden
steve at holdenweb.com
Sun Feb 15 15:36:15 EST 2009
John Nagle wrote:
> Benjamin Kaplan wrote:
>> On Sun, Feb 15, 2009 at 11:57 AM, John Nagle <nagle at animats.com> wrote:
>>
>>> Benjamin Peterson wrote:
>
>> Because b'x' is NOT a bytearray. It is a bytes object. When you
>> actually use
>> a bytearray, it behaves like you expect.
>>>>> type(b'x')
>> <class 'bytes'>
>>>>> type(bytearray(b'x'))
>> <class 'bytearray'>
>>>>> ba = bytearray(b'abc')
>>>>> ba[0] + ba[1]
>> 195
>
> That's indeed how Python 2.6 works. But that's not how
> PEP 3137 says it's supposed to work.
>
> Guido:
>
> "I propose the following type names at the Python level:
>
> * bytes is an immutable array of bytes (PyString)
> * bytearray is a mutable array of bytes (PyBytes)"
>
> ...
>
> "Indexing bytes and bytearray returns small ints (like the bytes type in
> 3.0a1, and like lists or array.array('B'))."
> (Not true in Python 2.6 - indexing a "bytes" object returns a "bytes"
> object with length 1.)
>
> "b1 + b2: concatenation. With mixed bytes/bytearray operands, the return
> type is
> that of the first argument (this seems arbitrary until you consider how
> += works)."
> (Not true in Python 2.6 - concatenation returns a bytearray in both cases.)
>
> Is this a bug, a feature, a documentation error, or bad design?
>
It's a feature. In fact all that was done to accommodate easier
migration to 3.x is easily shown in one statement:
>>> str is bytes
True
>>>
So that's why bytes works the way it does in 2.6 ... hence my contested
description of it as an "ugly hack". I am happy to withdraw "ugly", but
I think "hack" could still be held to apply.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list