5

Python eval is quite slow. I need to evaluate simple boolean expression with logical operators (like "True or False"). I am doing this for thousands of line of data and eval is a huge bottleneck in terms of performance. It's really slow.. Any alternative approaches?

I tried creating a dict of possible expression combinations and their expected output, but this is really ugly!

I have the following code at the moment:

eval('%s %s %s' % (True, operator, False)) 
2
  • 3
    What exactly are you doing? In 99% of the cases people who use eval really don't need it and will be much better of without it. I'm pretty sure you're in this group. Commented Oct 24, 2011 at 23:11
  • well, i just need to evaluate the boolean expression for thousands of lines. as you said, i do fall in the 99% category. the solution below is amazing! Commented Oct 24, 2011 at 23:18

2 Answers 2

14
import operator ops = { 'or': operator.or_, 'and': operator.and_ } print ops[op](True, False) 
Sign up to request clarification or add additional context in comments.

Comments

1

It's not clear to me how @CatPlusPlus's solution will evaluate any boolean expression. Here is an example from the pyparsing wiki examples page of a Boolean expression parser/evaluator. 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 Comment

I have implemented a parser that converts the complex expression into simple boolean expressions (precedence of operators, brackets etc.). At the end of the day I only need to evaluate something like "True or False" etc. so that's why the above solution works for me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.