How is this advantageous over str.format?
How is this advantageous over str.format?
Posted Jan 23, 2025 18:58 UTC (Thu) by rrolls (subscriber, #151126)In reply to: How is this advantageous over str.format? by siddh
Parent article: A revamped Python string-formatting proposal
It doesn't look particularly exciting in these textbook cases, but the benefits will quickly show themselves once you have more complicated real-world cases.
With t-strings, you could easily have something like this:
def render_item_row(item: Item) -> HTML:
return HTML(t"<tr><td>{item.name}</td><td>{item.date}</td><td>{item.author}</td></tr>")
Your "equivalent" would look like this:
def render_item_row(item: Item) -> HTML:
return HTML(
"<tr><td>{name}</td><td>{date}</td><td>{author}</td></tr>",
{"name": item.name, "date": item.date, "author": item.author}
)
which is unwieldy, unintuitive, and has a lot of boilerplate... or perhaps you might do
def render_item_row(item: Item) -> HTML:
return HTML(
"<tr><td>{name}</td><td>{date}</td><td>{author}</td></tr>",
dataclasses.asdict(item)
)
if Item happened to be a dataclass, but then as well as that requirement, the code doesn't make it obvious that those fields actually exist in the class.
Additionally, if you are using code assist, the 1st code block above will immediately get a red squiggly under any nonexistent field. But in both the 2nd and 3rd cases, code assist would not be able to help you if the text between { } was incorrect, or (in the 2nd case) if the dict keys were incorrect.
