What's the rationale for b"..." in this example?

Serhiy Storchaka storchaka at gmail.com
Tue May 15 13:38:09 EDT 2018


15.05.18 18:14, Skip Montanaro пише:
> Consider this:
> 
>>>> bytes("abc", encoding="utf-8")
> b'abc'
> 
> Looks reasonable. Then consider this:
> 
>>>> str(bytes("abc", encoding="utf-8"))
> "b'abc'"
> 
> Why is the b'...' bit still there? I suppose it's because I didn't tell it
> explicitly how to decode the bytes object, as when I do, I get the expected
> result:
> 
>>>> str(bytes("abc", encoding="utf-8"), encoding="utf-8")
> 'abc'

str() without 'encoding' and 'errors' calls __str__ which falls back to 
__repr__ by default.

bytes.__str__ falls back to bytes.__repr__, this makes errors of mixing 
bytes and strings more obvious. If run Python with the -b option, it 
will emit a BytesWarning first. If run it with -bb, it will become an error.

You can receive many interesting warning when run Python 2 with options 
-b and -3. Getting rid of these warnings will help with porting to 
Python 3 and may fix real bugs.




More information about the Python-list mailing list