Reputation: 6838
I'm trying to decode some text in base 64, and I don't understand why I get an error while trying to do that:
b'Zm9v'.decode('base64_codec')
The exception raised is: TypeError: expected bytes, not memoryview
PS: I know there's an alternative using the base64
module. But I'm interested in knowing the answer, just out of curiosity.
Thanks!
Upvotes: 1
Views: 563
Reputation: 1124318
Unfortunately, the bytes.decode()
and str.encode()
methods (rightly) only support codecs that also convert between types; bytes.decode()
must always return a str
object, while str.encode()
must return bytes
; see the original issue that introduced these codecs:
Codecs can work with arbitrary types, it's just that the helper methods on unicode and bytes objects only support one combination of types in Python 3.x.
So the specific error you see is caused by the fact that the bytes.decode()
method always expects to return a value of type str
. Similarly, the str.encode()
method balks at codecs that do not return bytes
as a return value:
>>> 'Ceasar'.encode('rot_13')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: encoder did not return a bytes object (type=str)
As such, for bytes-to-bytes and str-to-str codecs, you need to use the codecs
module directly:
import codecs
codecs.getdecoder('base64_codec')(b'Zm9v')[0]
Upvotes: 3