# Comments on plain text in f-strings

**URL:** <https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500>\
**Category:** Ideas\
**Created:** [September 20, 2024, 8:29am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500 "2024-09-20T08:29:35Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 8:29am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/1 "2024-09-20T08:29:35Z")

</div>

# Motivation

Comments are especially useful in multiline f-strings. There is no problem to insert them as part of the string, if it is supported downstream, like `re` module in verbose mode. But in other cases this can be either not possible or not readable (e.g no syntax highlighting).

Right now there is no documented way to add comments to f-strings. [Python docs](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) keep silence, [PEP 498](https://peps.python.org/pep-0498/#specification) says this is not possible.

_(Added later)_ It is possible to comment on f-string _expression_, but not on a _line of text_:

```python
f'''
foo = {
   1 + 2 # comment
}
...
text that needs a comment { # syntax error
} 
'''

```

There are [semi-solutions](https://stackoverflow.com/a/76302808/8067642) that abuse expressions syntax:

```python
f'{'comment':.0}'
f'{'comment'[:0]}'
f'{'comment' and ''}'
f'{'comment' * 0}'

```

But there is no preferred or recommended way to do it. Having a documented solution will provide some benefits, for example, allow syntax highlighting in IDE plugins.

# Possible solutions

> **Keeping aside introducing completely new syntax,**
>
> ```python
> f'text {.comment}'
> f'text {//comment}'
> f'text {--comment}'
> f'text {?comment}'
> f'text {?:comment}' # similar to re
> 
> ```

these could be:

1. Document one of “syntax hacks” above — this will allow plugin developers to implement syntax highlighting. Optimizations may be added to not produce excessive bytecode in this case.
2. Add new conversion `!i` or `!x` that will ignore the whole expression:

```python
f'{'commment'!i}'

```

Do you think any of these is reasonable?

---

<div class="post-metadata">

**Author:** ![blhsing](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/blhsing/32/25812_2.png) [@blhsing](https://discuss.python.org/u/blhsing)\
**Post date:** [September 20, 2024, 8:43am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/2 "2024-09-20T08:43:49Z")

</div>

How about breaking an f-string into pieces so you can add comments outside of them?

```python
s = (
    f'input = {x}, ' # comment about x
    f'output = {y}' # comment about y
)

```

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 8:51am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/3 "2024-09-20T08:51:26Z")

</div>

> [@blhsing](#):
>
> How about breaking an f-string into pieces

This is perfectly readable, but what about multiline portion of other language and IDE without plugin for inline syntax highlihting:

```python
RULES = f'''
bterm_1p : BCHAR_1P | BRANGE_1P {'1-st term in positive br exp':.0}
BCHAR_1P : /[^!]/
BRANGE_1P.1 : /[^!]-[^]]/

bterm_1n : BCHAR_1N | BRANGE_1N {'1-st term in negative br exp':.0}
BCHAR_1N : /./
BRANGE_1N.1 : /.-[^]]/

bterm_k : BCHAR_K | BRANGE_K {'K-th term':.0}
BCHAR_K : /[^]]/
BRANGE_K.1 : /[^]]-[^]]/
'''

```

(imagine there is no native comments syntax)

---

<div class="post-metadata">

**Author:** ![blhsing](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/blhsing/32/25812_2.png) [@blhsing](https://discuss.python.org/u/blhsing)\
**Post date:** [September 20, 2024, 9:32am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/4 "2024-09-20T09:32:21Z")

</div>

True that for a multiline string breaking it into pieces would make it uglier:

```python
RULES = (
'''
bterm_1p : BCHAR_1P | BRANGE_1P''' # 1-st term in positive br exp
'''
BCHAR_1P : /[^!]/
BRANGE_1P.1 : /[^!]-[^]]/

bterm_1n : BCHAR_1N | BRANGE_1N''' # 1-st term in negative br exp
'''
BCHAR_1N : /./
BRANGE_1N.1 : /.-[^]]/
'''
)

```

> [@makukha](#):
>
> 1. Document one of “syntax hacks” above — this will allow plugin developers to implement syntax highlighting. Optimizations may be added to not produce excessive bytecode in this case.

The `and 0` and `* 0` hacks are fairly optimized already:

```python
import dis

def f():
    return f'{'comment'*0}'

dis.dis(f)

```

outputs:

```plaintext
  3 RESUME 0

  4 LOAD_CONST 1 ('')
              FORMAT_SIMPLE
              RETURN_VALUE

```

> [@](#):
>
> 1. Add new conversion `!i` or `!x` that will ignore the whole expression:

Having to first make the comment a string and then add a conversion specifier still makes it look as ugly as those hacks though:

```python
f'''
bterm_1p : BCHAR_1P | BRANGE_1P {'comment'!i}
'''

```

I think a new syntax may be the better way to go if we are to add this feature. Perhaps we can borrow Jinja2’s comment syntax, which I find elegant:

```python
f'''
bterm_1p : BCHAR_1P | BRANGE_1P {# comment #}
'''

```

---

<div class="post-metadata">

**Author:** ![JamesParrott](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jamesparrott/32/10534_2.png) [@JamesParrott](https://discuss.python.org/u/JamesParrott)\
**Post date:** [September 20, 2024, 10:20am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/5 "2024-09-20T10:20:18Z")

</div>

It’s not obvious to me that the intention of the `{ :.0}`s are comments, and that I should read them.

I would refactor the multiline string to use Ben’s elegant suggestion.

---

<div class="post-metadata">

**Author:** ![pf\_moore](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pf_moore/32/35_2.png) [@pf\_moore](https://discuss.python.org/u/pf_moore)\
**Post date:** [September 20, 2024, 10:27am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/6 "2024-09-20T10:27:25Z")

</div>

> [@makukha](#):
>
> Comments are especially useful in multiline f-strings.

Why are they any more useful in multiline f-strings than in _normal_ multiline strings?

If the expressions you’re interprolating are complex, extract those into standalone variables calculated before the f-string, and comment the calculation just like any normal Python expression (which it is).

---

<div class="post-metadata">

**Author:** ![ronaldoussoren](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ronaldoussoren/32/61_2.png) [@ronaldoussoren](https://discuss.python.org/u/ronaldoussoren)\
**Post date:** [September 20, 2024, 10:30am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/7 "2024-09-20T10:30:39Z")

</div>

multi-line f-strings already support embedded comments (IIRC this was introduced in 3.12):

```python
>>> f"hello {
 ... 1+2 # a calculation
 ... }"
'hello 3'

```

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 10:35am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/8 "2024-09-20T10:35:00Z")

</div>

> [@ronaldoussoren](#):
>
> multi-line f-strings already support embedded comments

Yes, but in this case you are commenting expression, not the string text itself. Using it without expression does not work (syntax error):

```python
f'''
some text { # comment }
'''
f'''
some tex {
   # comment
}
'''

```

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 10:49am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/9 "2024-09-20T10:49:25Z")

</div>

> [@pf\_moore](#):
>
> Why are they any more useful in multiline f-strings than in _normal_ multiline strings?

The difference is that for normal multiline strings it is really impossible, and for f-strings there is a formatting syntax that gives some flexibility.

> [@pf\_moore](#):
>
> If the expressions you’re interprolating are complex, extract those into standalone variables calculated before the f-string, and comment the calculation just like any normal Python expression (which it is).

New variable names will be added when they are not needed. Such an artificial separation, when it was only needed to add some notes to string’s content, looks conceptually wrong to me.

Do you think there is no need in inline comments in multiline f-strings?

---

<div class="post-metadata">

**Author:** ![pf\_moore](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pf_moore/32/35_2.png) [@pf\_moore](https://discuss.python.org/u/pf_moore)\
**Post date:** [September 20, 2024, 10:58am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/10 "2024-09-20T10:58:07Z")

</div>

> [@makukha](#):
>
> Do you think there is no need in inline comments in multiline f-strings?

Yes, I do.

---

<div class="post-metadata">

**Author:** ![Paddy3118](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/paddy3118/32/1396_2.png) [@Paddy3118](https://discuss.python.org/u/Paddy3118)\
**Post date:** [September 20, 2024, 11:01am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/11 "2024-09-20T11:01:48Z")

</div>

+1 on the ` f"{'my comment' * 0}"`

---

<div class="post-metadata">

**Author:** ![ronaldoussoren](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ronaldoussoren/32/61_2.png) [@ronaldoussoren](https://discuss.python.org/u/ronaldoussoren)\
**Post date:** [September 20, 2024, 11:31am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/12 "2024-09-20T11:31:54Z")

</div>

> [@makukha](#):
>
> > [@ronaldoussoren](#):
> >
> > multi-line f-strings already support embedded comments
> 
> Yes, but in this case you are commenting expression, not the string text itself. Using it without expression does not work (syntax error):
> 
> ```python
> f'''
> some text { # comment }
> '''
> f'''
> some tex {
> # comment
> }
> '''
> 
> ```

Why would you want to use comments without an expression? That’s an honest question, I’d expect that the comments are primairily useful to explain complex expressions in the f-string.

BTW. A work around for the need to have an expression is to use one that evaluates to an empty string, such as… an empty string:

```python
f"{'' # some comment
}"

```

The newline is necessary because Python comments run to the end of a line, using slightly different rules inside f-strings would IMHO lead to additional semantic complexity and introduces more cases where it is no longer possible to copy and expression with a comment into an f-string.

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 11:43am UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/13 "2024-09-20T11:43:22Z")

</div>

> [@ronaldoussoren](#):
>
> Why would you want to use comments without an expression? That’s an honest question, I’d expect that the comments are primairily useful to explain complex expressions in the f-string.

Consider [this case](https://discuss.python.org/t/comments-on-text-in-f-strings/64500/3), or any other case when one wants to maintain a piece of text/code (SQL, grammar, XML, whatever) embedded in python file. There may be some expressions in this multiline string, as well as complex places where additional comments are needed.

The example above _could_ be broken into 3 separate strings, but what if it is a piece of XML or a highly nested SQL query, where breaking will harm readability? For SQL and XML I could add native inline comments, but for a format not supporting comments the only option would be breaking or using “hacks”. I’m not against hacks in this rare case, but I’d like to have syntax highlighting.

If not introducing completely new syntax for f-string comments, having an ignoring formatting conversion like `!i` does not seem a complex task (I could even try it myself) and won’t add complexity to Python grammar.

---

<div class="post-metadata">

**Author:** ![bschubert](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/bschubert/32/26920_2.png) [@bschubert](https://discuss.python.org/u/bschubert)\
**Post date:** [September 20, 2024, 12:15pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/14 "2024-09-20T12:15:06Z")

</div>

For something more readable than “syntax hacks” like `f"{'comment'*0}"`, you could define a function:

```python
def comment(*args: Any) -> Literal[""]:
    return ""

```

which can be used as:

```python
RULES = f"""
bterm_1p : BCHAR_1P | BRANGE_1P {comment('1-st term in positive br exp')}
BCHAR_1P : /[^!]/
BRANGE_1P.1 : /[^!]-[^]]/

bterm_1n : BCHAR_1N | BRANGE_1N {comment('1-st term in negative br exp')}
BCHAR_1N : /./
BRANGE_1N.1 : /.-[^]]/

bterm_k : BCHAR_K | BRANGE_K {comment('K-th term')}
BCHAR_K : /[^]]/
BRANGE_K.1 : /[^]]-[^]]/
"""

```

Granted, this won’t be optimized away like some syntax hacks, but I can’t imagine the speed difference being noticeable, especially if this is done only once at import time.

---

<div class="post-metadata">

**Author:** ![AndersMunch](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/andersmunch/32/12823_2.png) [@AndersMunch](https://discuss.python.org/u/AndersMunch)\
**Post date:** [September 20, 2024, 12:44pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/15 "2024-09-20T12:44:51Z")

</div>

> [@makukha](#):
>
> > [@pf\_moore](#):
> >
> > If the expressions you’re interprolating are complex, extract those into standalone variables calculated before the f-string, and comment the calculation just like any normal Python expression (which it is).
> 
> New variable names will be added when they are not needed. Such an artificial separation, when it was only needed to add some notes to string’s content, looks conceptually wrong to me.

On one hand the expression is complicated enough to warrant a comment.  
On the other hand the expression is not complicated enough to warrant a name.  
That is quite a combination.

Perhaps if you take the time to come up with a good name, you will not need the comment.

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 12:49pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/16 "2024-09-20T12:49:15Z")

</div>

> [@AndersMunch](#):
>
> Perhaps if you take the time to come up with a good name, you will not need the comment.

Yes, this would be true if it was about commenting on _expression_, but this post is about commenting on _a line of plain text_ in a string.

---

<div class="post-metadata">

**Author:** ![AndersMunch](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/andersmunch/32/12823_2.png) [@AndersMunch](https://discuss.python.org/u/AndersMunch)\
**Post date:** [September 20, 2024, 12:55pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/17 "2024-09-20T12:55:49Z")

</div>

Apologies for misunderstanding, I scanned the thread too hastily.

---

<div class="post-metadata">

**Author:** ![pf\_moore](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pf_moore/32/35_2.png) [@pf\_moore](https://discuss.python.org/u/pf_moore)\
**Post date:** [September 20, 2024, 1:13pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/18 "2024-09-20T13:13:56Z")

</div>

> [@makukha](#):
>
> this post is about commenting on _a line of plain text_ in a string.

And hence _my_ point. Why are f-strings different? The use case for commenting on a line of text in _any_ multi-line string is the same.

---

<div class="post-metadata">

**Author:** ![makukha](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/makukha/32/21764_2.png) [@makukha](https://discuss.python.org/u/makukha)\
**Post date:** [September 20, 2024, 1:19pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/19 "2024-09-20T13:19:55Z")

</div>

> [@pf\_moore](#):
>
> And hence _my_ point. Why are f-strings different? The use case for commenting on a line of text in _any_ multi-line string is the same.

I agree, being able to comment on line of normal string is the same use case. But is it possible?

---

<div class="post-metadata">

**Author:** ![pf\_moore](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pf_moore/32/35_2.png) [@pf\_moore](https://discuss.python.org/u/pf_moore)\
**Post date:** [September 20, 2024, 1:30pm UTC](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500/20 "2024-09-20T13:30:38Z")

</div>

Generally, use the comment capabilities in whatever language you’re embedding in a multi-line string. For example, in SQL

```python
sql = """\
SELECT
    name, salary -- the fields I need
FROM
    emp -- the employee table
"""

```

If you aren’t embedding a well-known language, I don’t understand your point about syntax highlighting. But it’s pretty easy to add post-processing to strip lines starting with (say) `#`:

```python
>>> a = """\
... one
... # Some junk
... two
... """
>>> print("".join(l for l in a.splitlines(keepends=True) if not l.startswith("#")))
one
two

>>>

```

I don’t think you’ve provided a compelling argument as to why we _need_ an additional comment syntax, especially not if it only works in f-strings and not in all multi-line strings. “It’s possible” isn’t an argument for doing something.

[Next page](https://discuss.python.org/t/comments-on-plain-text-in-f-strings/64500.md?page=2)
