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

Antoine Pitrou solipsis at pitrou.net
Fri Aug 24 19:55:31 CEST 2012


On Fri, 24 Aug 2012 13:26:49 -0400
Daniel Holth <dholth at gmail.com> 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.

You can use the -bb flag to raise BytesWarnings in such cases:

$ python3 -bb
Python 3.2.2+ (3.2:9ef20fbd340f, Oct 15 2011, 21:22:07) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str(b'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: str() on a bytes instance
>>> "%s" % (b'foo',)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: str() on a bytes instance
>>> "{}".format(b'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: str() on a bytes instance


Regards

Antoine.


-- 
Software development and contracting: http://pro.pitrou.net





More information about the Python-ideas mailing list