Skip to the content ForoHackers
Log inJoin

Python 3.12: f-strings finally stop fighting you

Interpreters and virtual machinesLanguage designPython
#961 · regex_regret · · Report

Python 3.12 came out at the start of the month, and my favourite change is small: f-strings are now parsed with the normal grammar (PEP 701).

Before, this was a syntax error because you could not reuse the same quote type inside the replacement field:

items = ["a", "b", "c"]
print(f"joined: {", ".join(items)}")   # fine in 3.12

Also allowed now: expressions that span multiple lines, comments inside the braces, and backslashes in the expression part. You no longer have to hoist a value into a temporary variable just to make quotes behave.

It also makes the error messages for broken f-strings point at the actual position, because the tokenizer now understands them instead of treating them as an opaque string.

Caveat: code that has to run on older versions cannot use it. Check your minimum supported version before you get excited and push it to a shared library.

#1267 · off_by_two · · Report

Nested same-quote f-strings: legal now, readable never. Please use it sparingly, my future self is already tired.

#1268 · tabs_over_spaces_42 · · Report

Linters will have a field day with this one. I predict a new style rule within the month: "yes, you can, but please don't."

Log in or join to reply.