Problem with ast.literal_eval on server?

After importing ast in a server module, I tried:

ast.literal_eval('1-0.24812818204100645-0.1')

But I get the error: ValueError: malformed node or string: <_ast.BinOp object at 0x7f5a11fd9a50>

The strange thing is, the same line of code works fine in other places. Just not in the server code in Anvil? Or am I doing something wrong?

The behaviour of ast.literal_eval is different across different versions of python.
I checked on python 3.7+ on my desktop and get the same behaviour, which make sense since anvil server code is running a python 3.7 environment.

You can just use eval on the server for this type of statement. eval('1 + 2 + 4')

linked resources:

ast — Abstract Syntax Trees — Python 3.12.3 documentation
python - ValueError: malformed string when using ast.literal_eval - Stack Overflow

Thank you! I learned something!

Interesting. It works with addition and subtraction with integers but not other operations or with floats. The reason being integer addition/subtraction it required for ast.literal_eval to work with complex numbers.

The solution, I guess, is to build a parser/tree evaluator for calculating these things (to avoid using eval) or - another solution I have tried which alkso works - to call a javascript function (using javascripts eval function).

Again, thank you!