|
|
Subscribe / Log in / New account

How is this advantageous over str.format?

How is this advantageous over str.format?

Posted Jan 27, 2025 9:59 UTC (Mon) by epa (subscriber, #39769)
In reply to: How is this advantageous over str.format? by rrolls
Parent article: A revamped Python string-formatting proposal

Agreed. This is something I have often found missing from Perl, too: how can I make a string with variable interpolation, but do my own custom interpolation?

It could bridge the gap between the safe but clunky way of creating an SQL statement with bind parameters, and the much more convenient and readable, yet dangerous, approach of pasting together an SQL string with variable interpolation. Most programming languages create too much "temptation" here. If you can say t"select * from mytable where id = {x}" and have it executed safely (which could be as simple as checking that x contains a number, not a string) then you won't have to choose between safety and comfort.

I would also use it for filenames. Writing f"/foo/bar/{leafname}" is handy but can be dangerous if leafname contains "..". You can use various libraries to build up a path from components, but again they're awkward compared to just writing out the path with interpolated parts. With t-strings, make_path(t"/foo/bar/{leafname}") could check that the value you're interpolating is a single path component, unless you explicitly permit otherwise.


to post comments

How is this advantageous over str.format?

Posted Jan 28, 2025 11:47 UTC (Tue) by taladar (subscriber, #68407) [Link] (1 responses)

SQL in particular might not be the best use case, not only are there statements you can create with string interpolation that can't be handled by parameter binding (e.g. anything that changes the structure of the statement), preparing statements also has other performance benefits over ad-hoc queries.

How is this advantageous over str.format?

Posted Jan 28, 2025 17:26 UTC (Tue) by epa (subscriber, #39769) [Link]

It does often perform better to make a prepared statement and then call it several times with different values of the bind parameters. But just as often, the difference is negligible. The query may be a one-off in the lifetime of the script. But anyway, if you have a t-string based interface

t'select name from mytable where id = {myid}'

then the SQL library is free to transform that into a prepared statement which it can execute hygienically and even cache for future calls of the same t-string.


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