[Python-ideas] format specifier for "not bytes"

MRAB python at mrabarnett.plus.com
Fri Aug 24 20:03:42 CEST 2012

On 24/08/2012 18:26, Daniel Holth wrote:
> While I was implementing JSON-JWS (JSON web signatures), a format
> which in Python 3 has to go from bytes > unicode > bytes > unicode
> several times in its construction, I notice I wrote a lot of bugs:
> "sha256=b'abcdef1234'"
> When I meant to say:
> "sha256=abcdef1234"
> Everything worked perfectly on Python 3 because the verifying code
> also generated the sha256=b'abcdef1234' as a comparison. I would have
> never noticed at all unless I had tried to verify the Python 3 output
> with Python 2.
> I know I'm a bad person for not having unit tests capable enough to
> catch this bug, a bug I wrote repeatedly in each layer of the bytes >
> unicode > bytes > unicode dance, and that there is no excuse for being
> confused at any time about the type of a variable, but I'm not willing
> to reform.
> Instead, I would like a new string formatting operator tentatively
> called 'notbytes': "sha256=%notbytes" % (b'abcdef1234'). It gives the
> same error as 'sha256='+b'abc1234' would: TypeError: Can't convert
> 'bytes' object to str implictly
Why are you singling out 'bytes'? The "%s" format specifier (or "{:s}"
with the .format method) will accept a whole range of values, including
ints and lists, which, when concatenated, will raise a TypeError. Why
should 'bytes' be different?

There _are_ certain number-only formats, so perhaps what you should be
asking for is a string-only format.

More information about the Python-ideas mailing list