Is the documentation for the bytes consdtructor wrong? (original) (raw)
February 9, 2025, 9:39pm 1
The built-in bytes
built-in function (class constructor) is shown here:
functions.html#func-bytes
as
class bytes(source=b'')
class bytes(source, encoding)
class bytes(source, encoding, errors)
and here:
stdtypes.html#bytes
as*class* bytes([*source* [, *encoding* [, *errors* ]]])
This shows to me that the encoding is not needed.
But if I try:>>> bytes('abc')
I getTypeError: string argument without an encoding
(Side note: b'abc'
works fine, with any ASCII characters)
(Side note: an empty bytes constructor bytes()
works fine)
Is the documentation wrong, or am I missing something?
smontanaro (Skip Montanaro) February 9, 2025, 10:28pm 2
Note that the single argument call requires a bytes object. If you pass a string object, you have to provide the encoding argument. I’m not sure if it’s completely clear in the page you referenced. If not, you could submit a bug report.
PeterL (Peter Lovett) February 9, 2025, 10:46pm 3
Oh, I see. I guess that’s implied by the source=b''
line, but it wasn’t clear to me. I don’t know if that could be made clear in the signature. Probably needs a comment like you just said: “the single argument call requires a bytes object.”
Stefan2 (Stefan) February 10, 2025, 2:04am 4
Not true, try bytes([1,2,3])
or bytes(3)
.
Stefan2 (Stefan) February 10, 2025, 2:09am 5
The doc says “constructor arguments are interpreted as for bytearray()” and the doc for that is directly above and says about source: 'If it is a string, you must also give the encoding".
Stefan2 (Stefan) February 10, 2025, 2:40am 6
Though I think that that bytearray()
link should be changed to go to that function instead of to the stdtypes page.
smontanaro (Skip Montanaro) February 10, 2025, 3:05am 7
True, since bytes objects are really immutable arrays of ints. I fooled myself looking at OP’s three examples where the first one explicitly showed a zero-length bytes literal as the argument. That kind of masked the nature of the argument’s type. (I don’t use bytes objects much.)