0

I've gone through dozens of answers looking for what seems a fairly simple request. I'd like to evaluate a basic math function provided as a string with a set of variables. Something like:

equation = "a * ( 1 - 1 / (  1 + (1/x - 1)^c ) ) + b"
y = evaluate( equation, { "a": 10, "b": 20, "c": 0.25, "x": 0.5 } )

In this example, equation is not known ahead of time and user specified (so no eval solutions).

It seems I should be able to do this with built-in Python libraries without the eval function, Pandas, SymPy or the like.

The library ast looked promising, but all the examples I found use Python 2 and the manual says several of the functions used are deprecated. Even then, I can't help but think there is something easier I'm just overlook--it takes less lines of code to have a web server. I'd take a modern example using ast though.

Any simple solutions using basic Python libraries?

A. Que
  • 31
  • 1
  • 1
  • 6
  • Does this answer your question? [Evaluating a mathematical expression without eval() on Python3](https://stackoverflow.com/questions/38860682/evaluating-a-mathematical-expression-without-eval-on-python3) – LeopardShark Feb 10 '22 at 13:50
  • @LeopardShark Nice, but the first answer to the question uses `eval` and the second uses an external library. I was hoping to just use Python's build-in libraries. The `simpleeval` library does illustrate how to use `ast`. – A. Que Feb 10 '22 at 15:02
  • The first answer checks the AST leaves against a whitelist, so it is secure. – LeopardShark Feb 10 '22 at 15:17

0 Answers0