PEP 701: Nested F-Strings in Python 3.12
Python 3.12 introduced PEP 701, an update that formalizes the syntax of formatted string literals (f-strings) by integrating them directly into Python's core PEG parser. This article explores the syntactic changes brought by PEP 701, detailing how it eliminates previous parsing limitations to allow quote reuse, multi-line comments, backslashes, and arbitrary levels of nested f-strings.
Parsing Formalization
Prior to Python 3.12, f-strings were not parsed using the standard Python grammar. Instead, the tokenizer manually handled the curly braces and internal expressions, treating the string's interior differently from regular Python code. This led to arbitrary restrictions and inconsistencies.
PEP 701 integrates the parsing of f-strings directly into the
official PEG parser. As a result, the tokens inside {...}
replacement fields are parsed exactly like standard Python expressions,
removing the legacy edge cases.
Quote Reuse and Arbitrary Nesting
Previously, inner expressions could not use the same quote type as the enclosing f-string. Developers had to alternate between single quotes, double quotes, and triple quotes, which capped nested f-strings to a maximum depth of four levels.
Under PEP 701, quote characters can be reused inside replacement fields without conflict:
# Valid in Python 3.12 (previously raised a SyntaxError)
result = f"{f"{f"{'deeply nested'}"}"}"Because quotes can be repeated, nesting can occur to an arbitrary depth, and dictionary lookups no longer require switching between single and double quotes:
# Both outer and inner quotes can be double quotes
status = f"Status: {user["profile"]["status"]}"Backslashes Inside Expressions
Before Python 3.12, using a backslash inside an f-string expression was strictly prohibited. Common operations, such as joining strings with a newline character, required defining a separate variable before interpolation.
PEP 701 removes this restriction. Backslashes and escape sequences
can now be placed directly inside {...} expressions:
words = ["Python", "3.12", "PEP", "701"]
# Valid in Python 3.12
output = f"List:\n{'\n'.join(words)}"Comments Inside Replacement Fields
Because expressions inside f-strings are now treated as regular
Python code, multi-line expressions inside {...} can
include standard Python comments (#). Previously, any
# inside a replacement field caused a syntax error.
info = f"Current total: {
sum([1, 2, 3]) # Calculating total inline
}"These changes make f-string syntax fully consistent with the rest of Python's grammar, simplifying string formatting and making complex nested templates easier to write and maintain.