simpleeval
simpleeval copied to clipboard
Make Eval Class Callable
so you could do:
>>> s = SimpleEval()
>>> s('22 + 20')
42
which would be rather sweet.
The way I'm currently using it, I have used the extension capabilities so that I can parse an expression a single time and then call it multiple times to perform the same operation on multiple variables. Here's the very simple code and I think that it could be useful as a general feature:
# Parse the given code into AST
def parse(self, code):
self.expr = code
self._ast = ast.parse(code)
# Run the parsed code with the variables in names available for use in the code
def __call__(self, names=None):
if names:
self.names.update(names)
return self._eval(self._ast)
Cool idea! I hadn't thought of doing multiple runs on different data. I'm exploring this a bit on the Dev branch.
Couldn't you do
def __call__(self, *args, **kwargs):
return self.eval(*args, **kwargs)
ya, I have this same use case, I want to parse the expression once, and then evaluate it many times with different variable values. I'm just hacking it for now:
expr = ast.parse("a+ b ").body[0].value
s = SimpleEval()
s.names = dict(a=1, b=2)
s._eval(expr)
s.names = dict(a=3, b=4)
s._eval(expr)
...
but it would be nicer if you could pass in the expression to parse, and have eval just run the precompiled thing:
s = SimpleEval(expr='a+b')
s.eval(names=dict(a=1, b=2))
I could make a PR for that if you think it's useful.
Is there still interest in this? Did anyone ever make a PR? We also have a use case for this
Closing this - I don't believe it's valuable any more.
the cached parse stuff covers some of it, and the rest could be easily done as a wrapper class outside simpleeval.
If there are things I've forgotten that are important, please raise a new issue.
Yes, that's what we were doing. We were hoping to have that included for others to use and to minimize the code we were carrying, but if it's not wanted, then we'll keep the wrapper. Thanks for all of your work on this.