Filtering objects matching a given logical formula
Question: I have an array of Python objects, and I would like to get all objects that
evaluate to true for a given logical formula.

Let's say the objects are tasks in a task tracking system. Each task has a
status, an assignee and a due date. Now I'd like to get all objects that
evaluate to true for this formula:

    
    
    (assignee=cdecker OR due=tomorrow) AND status=open
    

For things like the object fields (`assignee` and `status`) it would be a
simple matter of checking equality, whereas `due=tomorrow` would be a function
to be called on the object.

Is there a simple parser that I could use to parse the expression and then
evaluate it for all the objects in my starting set (basically wire all
literals to function calls)?


Answer: Try [pyparsing](http://pyparsing.wikispaces.com/). Here's a parser for a
grammar that supports equality, boolean ops and nested brackets:

    
    
    from pyparsing import *
    
    expr   = Forward()
    factor = Forward()
    term   = Forward()
    
    iand   = Literal("AND").suppress()
    ior    = Literal("OR").suppress()
    ieq    = Literal("=").suppress()
    lpar   = Literal("(").suppress()
    rpar   = Literal(")").suppress()
    ident  = Word(alphas)
    atom   = ident | lpar + expr + rpar
    
    factor << Group(atom + ZeroOrMore(ieq + atom))("equal")
    term   << Group(factor + ZeroOrMore(iand + term))("and")
    expr   << Group(term  + ZeroOrMore(ior + expr))("or")
    

You can apply this to your formulas to obtain tree-alike structures, which you
can evaluate at some point later, for example:

    
    
    formula = "(assignee=cdecker OR due=tomorrow) AND status=open"
    tree = expr.parseString(formula, parseAll=True)
    print tree.asXML()
    

