simpleeval
simpleeval copied to clipboard
Cache ast parsed expressions
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
Hello @chongr! Thanks for opening this PR. We checked the lines you've touched for PEP 8 issues, and found:
- In the file
simpleeval.py
:
Line 331:80: E501 line too long (85 > 79 characters)
Coverage increased (+0.003%) to 99.674% when pulling 07f7bc606f0c774fc31e4a7d61870b5977463620 on chongr:cache-ast-parsed-expressions into b47858d7153a05f64da16c4425c38f481e510d12 on danthedeckie:master.
Any chance we can get this merged?
Can this be merged?
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.
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.