simpleeval icon indicating copy to clipboard operation
simpleeval copied to clipboard

Make Eval Class Callable

Open danthedeckie opened this issue 8 years ago • 5 comments

so you could do:

>>> s = SimpleEval()
>>> s('22 + 20')
42

which would be rather sweet.

danthedeckie avatar Feb 05 '17 11:02 danthedeckie

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) 

dave-nm avatar Feb 06 '17 20:02 dave-nm

Cool idea! I hadn't thought of doing multiple runs on different data. I'm exploring this a bit on the Dev branch.

danthedeckie avatar Feb 09 '17 16:02 danthedeckie

Couldn't you do

    def __call__(self, *args, **kwargs):
        return self.eval(*args, **kwargs)

fionafibration avatar Jul 17 '18 20:07 fionafibration

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.

patricksurry avatar Dec 06 '18 15:12 patricksurry

Is there still interest in this? Did anyone ever make a PR? We also have a use case for this

chongr avatar Jul 17 '19 21:07 chongr

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.

danthedeckie avatar Feb 17 '23 09:02 danthedeckie

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.

daveisfera avatar Feb 17 '23 14:02 daveisfera