derivation: sick Python trick of the week
Greg Ewing (using news.cis.dfn.de)
wmwd2zz02 at sneakemail.com
Mon Feb 23 03:26:04 CET 2004
Robert Brewer wrote:
> In a fit of mad-scientist genius (get out the pitchforks and torches), I
> wondered if it might be faster to let Python do *all* the parsing, and
> just watch it work and take notes. That's what the code below does. The
> sick and twisted part is how one invokes this technique:
It's not really all that sick, or at least it's not a new
idea. I'm sure there's at least one DB module out there
somewhere that uses this technique.
> Yes, in line two we run comparisons and boolean operations on
> non-existent attributes of x, and discard the results! Sick.
That part is perhaps a bit too twisted. It's not really
necessary, you could just as well design it so you say
expr = (x.a == 3) & ((x.b > 1) | (x.b < -10))
> And it's
> *far* from obvious that 'x.a' should reduce to just 'a'.
In the case of database queries, you can make this seem
much more natural by having 'x' represent some meaningful
object such as a table.
db = open_database("favourite_fruits")
fruits = db.fruits
query = (fruits.kind == "apple") && (fruits.tastiness >= 3)
> I had to replace boolean 'and' and 'or' with binary calls in order to
> override them, and 'not' with 'neg'. That makes it even sicker.
Yes, that's the main nuisance with this technique. I have
a PEP idea floating around to make and/or/not overridable,
for this very purpose. Hmmm... does that make me sick?-)
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
More information about the Python-list