simpleeval icon indicating copy to clipboard operation
simpleeval copied to clipboard

Make Eval Class Callable

Open danthedeckie opened this issue 7 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