Search code examples
pythoneval

ast.literal_eval power support


How to evaluate user input mathematical expressions such as power safely? Tried using ast.literal_eval but it raises an exception.

>>> import ast
>>> ast.literal_eval('2**2')
ValueError: malformed node or string: <_ast.BinOp object at ...>

Solution

  • You can use seval package for arithmetic operations and literals safe evaluation.

    >>> import seval
    >>> seval.safe_eval('2 ** 2')
    4