|
|
Log in / Subscribe / Register

Could’ve been long ago

Could’ve been long ago

Posted Apr 22, 2025 7:11 UTC (Tue) by xi0n (guest, #138144)
Parent article: Template strings accepted for Python 3.14

So, this is basically format_args!() from Rust, producing an inspectable object containing the format string and its arguments. Neat, and the applications are quite obvious.

Funnily enough, this isn’t really tied to f-strings, other than the fact that the existence of f”” literals mandates this to be a special literal, too. One could easily imagine str.formatargs function, that takes same params as str.format but returns a Template, to have been added even to Python 2.x.


to post comments

Could’ve been long ago

Posted Apr 22, 2025 15:43 UTC (Tue) by NYKevin (subscriber, #129325) [Link]

This nomintally existed in 2.x. It was (and nominally still is) spelled string.Template, but unfortunately, you had to implement 90% of it yourself, because it just provides a top-level entry point for overriding the whole interpolation: https://docs.python.org/3/library/string.html#template-st...

Supposedly it is used for i18n, but I have no familiarity with that use case. If t-strings end up being wildly popular, they might plausibly end up absorbing and replacing this use case.

Could’ve been long ago

Posted Apr 23, 2025 7:29 UTC (Wed) by iabervon (subscriber, #722) [Link]

As compared to str.format(), there's been string.Formatter to allow for producing something other than a str and there's been f-strings to allow for writing the arguments inside the format string literal. This is essentially combining those differences (with improvements to the API from experience with string.Formatter and for the fact that Interpolation can actually be given the text of the expression).

While it is mostly not functionally different from format_args!(), it's actually a huge ergonomic benefit to be able to write the arguments interleaved with the string literal text. For example, this allows for writing code that doesn't have SQL injection vulnerabilities that is actually more obvious and readable than code that does have SQL injection vulnerabilities. You've had to tell people why they must not write "SELECT * FROM users WHERE name='"+name+"' AND password='"+password'";", or f"SELECT * FROM users WHERE name='{name}' AND password='{password}';", and have to instead write execute("SELECT * FROM users WHERE name={} AND password={};", name, password), which is harder to read but actually secure. But now they can use t"SELECT * FROM users WHERE name={name} AND password={password};" and the code you can read in order without any extra quotes is actually correct.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds