Why does base64.b64encode() return a bytes object?

前端 未结 2 1182
不思量自难忘°
不思量自难忘° 2020-12-17 07:54

The purpose of base64.b64encode() is to convert binary data into ASCII-safe \"text\". However, the method returns an object of type bytes:

>&         


        
2条回答
  •  失恋的感觉
    2020-12-17 08:16

    It's impossible for b64encode() to know what you want to do with its output.

    While in many cases you may want to treat the encoded value as text, in many others – for example, sending it over a network – you may instead want to treat it as bytes.

    Since b64encode() can't know, it refuses to guess. And since the input is bytes, the output remains the same type, rather than being implicitly coerced to str.

    As you point out, decoding the output to str is straightforward:

    base64.b64encode(b'abc').decode('ascii')
    

    ... as well as being explicit about the result.

    As an aside, it's worth noting that although base64.b64decode() (note: decode, not encode) has accepted str since version 3.3, the change was somewhat controversial.

提交回复
热议问题