Is there a way to include a comment in an f-string?

Viewed 734

It would be useful for mo to include a comment in an f-string. For instance, take this code:

f"""
<a
   href="{ escape(url) }"
   target="_blank" { # users expect link to open in new tab }
>bla</a>
"""

It would be nice if this code was equivalent to:

f"""
<a
   href="{ escape(url) }"
   target="_blank" 
>bla</a>
"""

You can include full Python expressions in between the curly brackets, but it looks like you can't include comments. Am I correct? Is there a way to do this?

3 Answers

From PEP498:

Comments, using the '#' character, are not allowed inside an expression.

There is no way to comment other than putting a '#' character in Python, so it is not possible.

No. There is no comment in f-string.

When building a str, template engines may be overkill. Joining a list of str may be desirable.

s = ''.join([
    '<a',
    f' href="{escape(url)}"',
    ' target="_blank">',
    # users expect link to open in new tab
    'bla</a>',
])

You cannot write a comment inside an expression. But you can write a string in multiple fragments and write a comment between 2 fragments provided the next fragment starts on a different line:

s = (f"""
<a
   href="{ escape(url) }"
   target="_blank" """ # users expect link to open in new tab
f""">bla</a>
""")
Related