[Python-3000] Please don't kill the % operator...
"Martin v. Löwis"
martin at v.loewis.de
Fri Aug 17 00:45:32 CEST 2007
> There's one other problem that I see, though it might be minor or
> infrequent enough not to matter. %s positional placeholders are
> easily to generate programmatically than {#} placeholders. Think
> about translating this:
>
> def make_query(flag1, flag2):
> base_query = 'SELECT %s from %s WHERE name = %s '
> if flag1:
> base_query += 'AND age = %s '
> if flag2:
> base_query += 'AND height = %s '
> base_query = 'AND gender = %s'
> return base_query
Of course, *this* specific example is flawed: you are likely to
pass the result to a DB-API library, which supports %s as a
placeholder independent of whether strings support the modulo
operator (it is then flawed also in that you don't typically
have placeholders for the result fields and table name - not sure
whether you even can in DB-API).
If I had to generate a computed format string, I'd probably
use the named placeholders, rather than the indexed ones.
base_query = 'SELECT {field} FROM {table} WHERE name = {name} '
if flag1:
base_query += 'AND age = {age} '
if flag2:
base_query += 'AND height = {height} '
base_query += 'AND gender = {gender}'
return base_query
Regards,
Martin
More information about the Python-3000
mailing list