Re: Use of locals() with SQL placeholders
Chris Angelico via Python-list <[email protected]>
| Newsgroups | gmane.comp.python.general |
|---|---|
| Message-ID | <CAPTjJmpbF8RV=LPnkWqbn7_mxpzNCVyMg8L8feHLx68_2GWVuQ@mail.gmail.com> |
On Fri, 4 Sept 2026 at 06:41, dn via Python-list <[email protected]> wrote: > However, this is weaker than it may sound. Firstly, type-hints work at > IDE-time, cf execution-time. Secondly, it is possible to inject/append > to the t-string, eg `sql + f"Little Bobby Tables"` because there is no > guard/it's 'silent' and there's no type-error. Hence the accusation of > t-strings being un-safe when compared to the 'traditional' alternatives > provided at the boundary. Not sure what you mean about inject/append here - if sql is a t-string (or to be more precise, a template), you can't concatenate a str to it: >>> id = 42 >>> sql = t"select * from users where id = {id}" >>> sql + " or 1=1" Traceback (most recent call last): File "<python-input-3>", line 1, in <module> sql + " or 1=1" ~~~~^~~~~~~~~~~ TypeError: can only concatenate string.templatelib.Template (not "str") to string.templatelib.Template >>> So I'm not sure what aspect of them is unsafe. Personally, I tend not to have the repetition (I don't put stuff into local variables just to then interpolate it into a string), so I'm much more comfortable with an explicit dictionary of bindings. But for those who actually are in the situation to benefit from them, t-strings should be safe. ChrisA