>>> bytes.fromsize(3)
b'\x00\x00\x00'
>>> bytearray.fromsize(3)
bytearray(b'\x00\x00\x00')
>>> bytes.fromsize(5, b'\x0a')
b'\x0a\x0a\x0a\x0a\x0a'
>>> bytearray.fromsize(5, fill=b'\x0a')
bytearray(b'\x0a\x0a\x0a\x0a\x0a')
fromsize
will behave just as the current constructors behave when passed a
single integer, while allowing for non-zero fill values when needed.
As binary counterparts to the text chr
function, this PEP proposes
the addition of an explicit fromint
alternative constructor as a class
method on both bytes
and bytearray
:
>>> bytes.fromint(65)
>>> bytearray.fromint(65)
bytearray(b'A')
These methods will only accept integers in the range 0 to 255 (inclusive):
>>> bytes.fromint(512)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: integer must be in range(0, 256)
>>> bytes.fromint(1.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
The documentation of the ord
builtin will be updated to explicitly note
that bytes.fromint
is the primary inverse operation for binary data, while
chr
is the inverse operation for text data, and that bytearray.fromint
also exists.
Behaviorally, bytes.fromint(x)
will be equivalent to the current
bytes([x])
(and similarly for bytearray
). The new spelling is
expected to be easier to discover and easier to read (especially when used
in conjunction with indexing operations on binary sequence types).
As a separate method, the new spelling will also work better with higher
order functions like map
.
These new methods intentionally do NOT offer the same level of general integer
support as the existing int.to_bytes
conversion method, which allows
arbitrarily large integers to be converted to arbitrarily long bytes objects. The
restriction to only accept positive integers that fit in a single byte means
that no byte order information is needed, and there is no need to handle
negative numbers. The documentation of the new methods will refer readers to
int.to_bytes
for use cases where handling of arbitrary integers is needed.
This PEP proposes that bytes
and bytearray
gain the method getbyte
which will always return bytes
:
>>> b'abc'.getbyte(0)
If an index is asked for that doesn’t exist, IndexError
is raised:
>>> b'abc'.getbyte(9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index out of range
This PEP proposes that bytes
and bytearray
gain an optimised
iterbytes
method that produces length 1 bytes
objects rather than
integers:
for x in data.iterbytes():
# x is a length 1 ``bytes`` object, rather than an integer
For example:
>>> tuple(b"ABC".iterbytes())
(b'A', b'B', b'C')
Zero-initialised sequences can be created via sequence repetition: