r/Python • • Sep 09 '15

Pep 498 approved. :(

https://www.python.org/dev/peps/pep-0498/
285 Upvotes

324 comments sorted by

View all comments

Show parent comments

2

u/zahlman the heretic Sep 09 '15

Why add this piece of arcane syntax

It is not being added. This "conversion" step has always been a part of the format string syntax for .format(). Only the a conversion is being "added", and that's already in 3.5 - which I'd say is just correcting an oversight, given that the builtin ascii does the same sort of thing that str and repr do.

The double brace is also super weird.

It's again the same escaping that .format() uses.

Why would escaping braces not use backslashes, like, y'know, every other thing that needs to be escaped?

Because that isn't even true for the other main method of formatting:

>>> "spam \%s spam %s and spam" % "eggs"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "spam %%s spam %s and spam" % "eggs"
'spam %s spam eggs and spam'

See? It even uses the same doubling-up approach. It can't just use a single backslash because that's interpreted (to determine the contents of the format string) at compile-time, while the interpolation is done at run-time. But it doesn't work with a double backslash, either:

>>> "spam \\%s spam %s and spam" % "eggs"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

Sure, it works for regexes, but that's more for traditional/historical reasons. (And it's awkward enough that people end up using raw strings for their regexes anyway.)

0

u/LpSamuelm Sep 09 '15

Yes, I do suppose these criticisms are valid for the earlier string formatting methods too, then.

Interesting point about the compile-time vs. runtime thing, though I do think that difference shouldn't really have to shine through to the user.