simpleeval icon indicating copy to clipboard operation
simpleeval copied to clipboard

Cache ast parsed expressions

Open chongr opened this issue 4 years ago • 5 comments

Should allow the use cases outlined in https://github.com/danthedeckie/simpleeval/issues/25 Basically the expressions that have already gone through ast.parse are cached in the SimpleEval class. Whenever eval is called it checks if the expression had been parsed previously. If so it will used the previously ast.parse result that was run on the expression the first time it ran.

If you agree with this PR for this use case I will add tests for this feature (also might be worth adding some LRU type configurable logic...). If not I think that the _eval function should be renamed to something like eval_ast to signify that it is a public method that can be used to cover use cases like those in the linked issues.

Either way let me know what you think

chongr avatar Jul 23 '19 20:07 chongr

Hello @chongr! Thanks for opening this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 331:80: E501 line too long (85 > 79 characters)

pep8speaks avatar Jul 23 '19 20:07 pep8speaks

Coverage Status

Coverage increased (+0.003%) to 99.674% when pulling 07f7bc606f0c774fc31e4a7d61870b5977463620 on chongr:cache-ast-parsed-expressions into b47858d7153a05f64da16c4425c38f481e510d12 on danthedeckie:master.

coveralls avatar Jul 23 '19 20:07 coveralls

Any chance we can get this merged?

svsaraf avatar May 29 '20 15:05 svsaraf

Can this be merged?

suiyuan2009 avatar Apr 05 '21 13:04 suiyuan2009

There's a better solution.

    def eval(self, expr):
        """ evaluate an expresssion, using the operators, functions and
            names previously set up. """
        if isinstance(expr, str):
             self.expr = expr
             node = ast.parse(expr.strip()).body[0]
        else:
            self.expr = ast.dump(expr)
            node = expr 
        return self._eval(node)

Then if you want the parsing done once (or with different parse parameters. You can just pass the node in.

earthastronaut avatar Aug 05 '21 22:08 earthastronaut

I'm closing this PR, as 0.9.13 now includes a separated parse and eval methods, which allows you cache the parsed AST tree outside of SimpleEval pretty easily.

danthedeckie avatar Feb 17 '23 09:02 danthedeckie