[Python-ideas] Fixing the Python 3 bytes constructor

Steven D'Aprano steve at pearwood.info
Fri Mar 28 11:50:28 CET 2014

On Fri, Mar 28, 2014 at 08:27:33PM +1000, Nick Coghlan wrote:
> One of the current annoyances with the bytes type in Python 3 is the
> way the constructor handles integers:

> 1. Add "bytes.chr" such that "bytes.chr(x)" is equivalent to the PEP
> 361 defined "b'%c' % x"

+1 on the concept, but please not "chr". How about bytes.byte(x)? That 
emphasises that you are dealing with a single byte, and avoids 
conflating chars (strings of length 1) with bytes.

> 2. Add "bytearray.allnull" and "bytes.allnull" such that
> "bytearray.allnull(x)" is equivalent to the current "bytearray(x)" int
> handling

+1 on bytearray.allnull, with a mild preference for spelling it "zeroes" 

I'm indifferent about bytes.allnull. I'm not sure why I would use it 
in preference to b'\0'*x, or for that matter why I would use it at all. 
I suppose if there's a bytearray.allnul, for symmetry there should be a 
bytes.allnul as well.

> 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)


> Anyway, what do people think? Does anyone actually *like* the way the
> bytes constructor in Python 3 currently handles integers and want to
> keep it forever? 

Not me!

> Does the above proposal sound like a reasonable
> suggestion for improvement in 3.5? Does this hit PEP territory, since
> it's changing the signature and API of a builtin?

On the vanishingly small chance that there is universal agreement on 
this, and a minimum of bike-shedding, I think it would still be useful 
to write up a brief half page PEP linking to the discussion here.


More information about the Python-ideas mailing list