Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 368
Flimm Avatar asked Jan 25 '23 00:01

Flimm


2 Answers

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>',
])
like image 35
Aaron Avatar answered Jan 28 '23 13:01

Aaron


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.

like image 74
Asocia Avatar answered Jan 28 '23 13:01

Asocia