Python's eval alternative

Python eval pretty slow. I need to evaluate a simple boolean expression using boolean operators (for example, True or False). I do this for thousands of rows of data, and eval is a huge performance bottleneck. This is really slow .. Any alternative approaches?

I tried to create a dict possible combinations of expressions and their expected result, but it is really ugly!

I have the following code at the moment:

 eval('%s %s %s' % (True, operator, False)) 
+4
source share
2 answers
 import operator ops = { 'or': operator.or_, 'and': operator.and_ } print ops[op](True, False) 
+13
source

I don’t understand how the @CatPlusPlus solution will evaluate any boolean expression. The following is an example from the Boolean expression parser / evaluationator wiki example page. Here are the test cases for this script:

 p = True q = False r = True test = ["p and not q", "not not p", "not(p and q)", "q or not p and r", "q or not (p and r)", "p or q or r", "p or q or r and False", ] for t in test: res = boolExpr.parseString(t)[0] print t,'\n', res, '=', bool(res),'\n' 
+1
source

All Articles