Since the question specifically asked about Python comments in f-strings, Asocia's answer is technically correct; You cannot include Python comments between curly brackets in f-strings.
However, if you are willing to abuse other Python features to emulate comments, then there are other ways to incorporate text into an f-string in source code such that it will not be included in the output of the f-string at run time.
For example:
f"""
<a
href="{ escape(url) }"
target="_blank"{ '# users expect link to open in new tab' :.0 }
>bla</a>
"""
Some options:
{ 'my comment' :.0 }
This works by putting the comment in a single-quoted Python string, then using a "format specifier" in the f-string expression to truncate this string to zero length. (":" is a special separator character in f-string expressions, and everything after it is interpreted as a format specifier. The ".0" format specifier sets a "precision" of zero which truncates the string to zero length.)
{ '# my comment' :.0 }
This is the same as the above option, but adding "#" at the beginning of the string may help make it more obvious that this is intended to be a comment.
{ 'my comment' [:0] }
This uses a Python "slice" to return a zero-length substring of the Python string, instead of using a "format specifier" to truncate the string.
{ 'my comment' and '' }
This works by using the and
boolean expression to evaluate the first string then (since any non-empty string is evaluated as true) return the second (empty) string.
{ 'my comment' if False else '' }
This works by using a conditional expression (sometimes called a "ternary operator") to ignore the first string and return the second (empty) string.
{ comment('my comment') }
If you are worried about other developers not understanding how the above expressions work or not recognizing that they are intended to be comments, then this may be more explicit. This requires a comment
function to be defined separately as shown below.
Example comment
function definition:
def comment(_):
return ''