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)?
Try pyparsing. Here’s a parser for a grammar that supports equality, boolean ops and nested brackets:
You can apply this to your formulas to obtain tree-alike structures, which you can evaluate at some point later, for example: