[Python-ideas] Fixing the Python 3 bytes constructor

Brett Cannon bcannon at gmail.com
Sat Mar 29 14:49:14 CET 2014


On Fri Mar 28 2014 at 10:29:36 AM, Barry Warsaw <barry at python.org> wrote:

> Great idea Nick.  If I may dip my brush in some paint buckets.
>
> On Mar 28, 2014, at 08:27 PM, Nick Coghlan wrote:
>
> >However, during a conversation today, a possible solution occurred to
> >me: a "bytes.chr" class method, that served as an alternate
> >constructor. That idea results in the following 3 part proposal:
> >
> >1. Add "bytes.chr" such that "bytes.chr(x)" is equivalent to the PEP
> >361 defined "b'%c' % x"
>
> I agree with Steven that bytes.byte() is a better spelling.
>

If we are going to add a classmethod, then yes, otherwise just stick with
byte([x]).


>
> >2. Add "bytearray.allnull" and "bytes.allnull" such that
> >"bytearray.allnull(x)" is equivalent to the current "bytearray(x)" int
> >handling
>
> I like bytearray.fill() for this.  The first argument would be the fill
> count,
> but it could take an optional second argument for the byte value to fill it
> with, which would of course default to zero.  E.g.
>
> >>> bytearray.fill(5)
> bytearray(b'\x00\x00\x00\x00\x00')
> >>> bytearray.fill(5, 97)
> bytearray(b'aaaaa')
>

I agree that if we are going to keep a classmethod to do this it should be
like str.zfill(). Otherwise just rely on the multiply operator.


>
> >3. Deprecate the current "bytes(x)" and "bytearray(x)" int handling as
> >not only ambiguous, but actually a genuine bug magnet (it's way too
> >easy to accidentally pass a large integer and try to allocate a
> >ridiculously large bytes object)
>
> +1
>

+1


>
> >Does the above proposal sound like a reasonable suggestion for
> improvement in
> >3.5?
>
> Very much so.
>
> >Does this hit PEP territory, since it's changing the signature and API
> >of a builtin?
>
> I don't much care either way.  A PEP is not *wrong* (especially if we all
> start painting), but I think a tracker issue would be fine too.
>

PEP wouldn't hurt since it's a core type, but I'm not going to scream for
it if Guido just says "fine" at the language summit or something (should we
discuss this there?).


Overall I think I'm +1 on the "simplify the API" by dropping the
constructor issue and relying on the multiply operator instead of coming up
with a new method. Same with bytes([x]) if you need to convert a single int.

I'm also +1 on Benjamin's idea of the iterate-as-bytes addition. That just
leaves the inability to index into bytes and get back a single as the
biggest annoyance in the bytes API.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140329/ba76b561/attachment.html>


More information about the Python-ideas mailing list