[Python-ideas] Fixing the Python 3 bytes constructor
Serhiy Storchaka
storchaka at gmail.com
Fri Mar 28 22:09:15 CET 2014
28.03.14 12:27, Nick Coghlan написав(ла):
> The other consequence of this is that's currently no neat way to
> convert the integers produced by various bytes APIs back to a length
> one bytes object - we have no binary equivalent of "chr" to convert an
> integer in the range 0-255 inclusive to its bytes counterpart. The
> acceptance of PEP 361 means we'll get another option (b"%c".__mod__)
> but that's hardly what anyone would call obvious.
AFAIK currently the fastest way is:
packB = struct.Struct('B').pack
But lambda x: bytes([x]) looks most obvious.
> 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"
-0. This is not very needed method and is not worth the language
complication. bytes([x]) works pretty good in most cases.
> 2. Add "bytearray.allnull" and "bytes.allnull" such that
> "bytearray.allnull(x)" is equivalent to the current "bytearray(x)" int
> handling
-1. b'\0' * x does this.
> 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)
+0.
More information about the Python-ideas
mailing list