Style recommendation around f-strings and continuations

Hello,

It is quite common to use f-strings for large error messages that would not fit on a single line of code, depending on your conventions (and readability preferences).

The idiomatic way around this is, of course, string continuations. However, it then comes up relatively often that some segments of the string continuation don’t have a formatting pattern in them.

What should be the stylistic preference then? Should all segments of a f-string continuation have a f in front of them, or only those that are actually templated?

Concrete example: which one should be preferred and why? (possible concerns include: maintainability, readability, performance)

    raise click.ClickException(
        f"There is no service/image defined in docker-compose.yml with "
        f"the given name: {e}"
    )

or

    raise click.ClickException(
        "There is no service/image defined in docker-compose.yml with "
        f"the given name: {e}"
    )

(please don’t answer that the error message should be phrased more concisely, or that I should just accept a larger line width - that’s off-topic here :slight_smile: )

2 Likes

I encounter this as well, and also prefer the opening quotes to be aligned.

Unnecessary f-strings break a common formatting rule: f-string-missing-placeholders (F541) | Ruff

I’m not sure of the reason for that, but personally I like to rule out bugs, and to quickly deduce that a line cannot contain an arbitrary Python expression (e.g. if it’s just a string literal, without having to read the whole string). Removal of a single character is very cheap, and only compromises subjective code aesthetics.

3 Likes

Me too, i.e.

raise click.ClickException(
         "There is no service/image defined in docker-compose.yml with "
        f"the given name: {e}"
    )
1 Like

f-strings for all segments. In addition to quote alignment, it makes later editing slightly more foolproof, in my mind. For instance, if I was to modify a segment to include a {…} chunk, the odds are that on the first go-round I would forget to add the “f” prefix, necessitating a second go-round.

7 Likes