[Python-ideas] Fixing the Python 3 bytes constructor

Ron Adam ron3200 at gmail.com
Fri Mar 28 14:41:02 CET 2014



On 03/28/2014 06:27 AM, 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'd expect to use it this way...

     bytes.chr('3')

Which wouldn't be correct.



We have this...

 >>> (3).to_bytes(1,"little")
b'\x03'


OR...

 >>> def hexclean(h):
...     if h.startswith('0x'):
...         h = h[2:]
...     if not len(h)//2:
...         h = '0' + h
...     return h
...
 >>> bytes.fromhex(hexclean(hex(3)))
b'\x03'


Both of those seem like way too much work to me.



Bytes is a container object, so it makes sense to do...

    bytes([3])



The other interface you're suggesting is more along the lines of converting 
an object to bytes.  That would be a nice feature if it can be made to work 
with more objects, and then covert back again.  (even if only a few types 
was supported)

     b_three = bytes.from_obj(3)

     three = b_three.to_obj(int)


That wouldn't be limited to values between 0 and 255 like the hex version 
above.  (it doesn't need a length, or byteorder args.)



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

Numpy uses zeros and shape...

 >>> y = np.zeros((2, 3, 4))
 >>> y.shape
(2, 3, 4)

(Without the e.)  I'm not sure if it's a good idea to use zeros with a 
different signature.

There has been mentioned, that adding multidimensional slicing to python 
may be done.  So it may be a good idea to follow numpy's usage.




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

Agree


Cheers,
    Ron



More information about the Python-ideas mailing list