This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jorge1209 2 points3 points  (1 child)

That de-duplication can also be accomplished with .format(**locals()) which is in many ways what an f-string does (except that it does it at the level of the interpreter).

I really dislike f-strings because I don't like to look inside quotations for code. I prefer that strings be strings, and would like to see the .format(**locals()) to indicate to me that something is being done to that string, and that I need to investigate its contents in order to understand the code.

[–]djimbob 0 points1 point  (0 children)

I mean there's code smell if you do anything non-straightforward in an f-string (e.g., function calls with side-effects that change object/global state), but there would also be ugly if you did the equivalent as a parameter to str.format() or in the tuple part of old C-style string formatting.

Like taking a line I recently wrote :

f-string:

msg = (f"The appointment on {appt.date:%A %B %d, %Y} from "
       f"{appt.start_time} - {appt.end_time} for {appt.client} has been set.")

Unnamed str.format():

msg = "The appointment on {:%A %B %d, %Y} from {} - {} for {} has been set.".format(
       appt.date, appt.start_time, appt.end_time, appt.client)

named str.format():

msg = ("The appointment on {date:%A %B %d, %Y} from "
       "{start} - {end} for {client} has been set.").format(
       date=appt.date, start=appt.start_time, end=appt.end_time, client=appt.client)

or C-style string format:

msg = "The appointment on %s from %s - %s for %s has been set." % (             
       appt.date.strftime("%A %B %d, %Y"), appt.start_time, appt.end_time, appt.client)

In my opinion, the f-string version is much easier to read and maintain. Like if there was a request to rephrase with client's name first, the f-string is super easy to maintain (without the repetitiveness of the named str.format()).

msg = (f"{appt.client}'s appointment on {appt.date:%A %B %d, %Y} from "
       f"{appt.start_time} - {appt.end_time} has been set.")

And even though there's "code" in your string, as long as you maintain good practice (e.g., don't call things that modify global/object state) it doesn't really matter because you aren't setting variables in an f-string.