Checking each item in m.group()?

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jun 3 02:49:11 CEST 2008


Gilles Ganault wrote:
> On Mon, 2 Jun 2008 12:06:21 -0700 (PDT), Matimus <mccredie at gmail.com>
> wrote:
>> Here is a brief example. Note that this code is very insecure ....
> 
>> sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')"%tuple(
>>        (c, "NULL")[c == ''] for c in m.groups()
>>        )
> I don't understand this syntax :-/
(c, "NULL") is  a tuple; it is being indexed by the boolean "c == ''"
Since False is 0, and True is 1, the expression picks out "NULL"
exactly when c is the zero-length string.

A more idiomatic Python way of writing this (for the very special case
of '' or 0 or 0.0, or ...) is
     sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')" % tuple(
                                       (c or "NULL") for c in m.groups())

You can avoid problems w/ possible 0s or 0.0s or .. by using:
                                   (str(c) or "NULL") for c in groups())

the "or" (or a similar "and" trick) will continue to work.  The
different "empty" or "nothing" values of a data type are treated as
false in part to allow such shenanigans.  If used sparingly, it make
your code clearer, but over-use can make the reader scratch his head in 
wonder.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list