|
|
Subscribe / Log in / New account

A literal string type for Python

A literal string type for Python

Posted Apr 14, 2022 19:17 UTC (Thu) by iabervon (subscriber, #722)
Parent article: A literal string type for Python

A related thing I'd like to see would be something like ft"SELECT * FROM data WHERE user_id = {user_id}", that evaluates to ("SELECT * FROM data WHERE user_id = {}", ("user123",)), and then conn.execute((LiteralString, args)) could use the fact that Python has support for parsing format strings and working with the result in more interesting ways than making a new str. That is, it would replace each substitution with a "?" and add the value to the arguments, instead of replacing the substitution with the string representation of the value.

As a side note, secure coders these days have gotten really bad at writing insecure code. The example in the PEP just won't work at all, since it'll result in returning rows where data.user_id = data.user123 rather than ones where data.user_id = 'user123'. The insecure code that people would actually write is f"SELECT * FROM data WHERE user_id = '{user_id}';", with a set of single quotes that the attack could close.


to post comments

A literal string type for Python

Posted Apr 17, 2022 11:30 UTC (Sun) by felix.s (guest, #104710) [Link]

There is already a PEP for that, PEP 501. It was (as I recall) drafted in parallel with PEP 498, but the former was deferred because the Python developers wanted to get ‘further experience’ with naïve interpolation, as if they failed to understand that this will just incentivise developers to introduce bugs into their code by reaching for the injection-prone naïve f-strings instead, the very thing they are trying to paper over here. Or perhaps, if we take the deferral rationale seriously, they deliberately aimed for the PHP approach, where they first introduce a simplistic, half-baked design into the language, only to have to resort to painful after-the-fact fixes over the following years.

Meanwhile, JavaScript has had an equivalent to PEP 501 (tagged template strings) from the very start, added at the same time as naïve interpolation. I still find it hardly ideal (it's a bit too easy to simply forget the tag), and say what you want about the TC39, but at least they seem to understand developer incentives well. At this point, and I can’t believe I am saying this, I am starting to see JavaScript as a better Python than Python.


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