Есть ли синтаксический анализатор математических выражений + оценщик для Python?
Я не первый, кто задал этот вопрос, но ответы обычно указывают на eval()
. Например, это можно сделать:
>>> safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'abs']
>>> safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
>>> s = "2+3"
>>> eval(s, {"__builtins__":None}, safe_dict)
5
Но это не безопасно:
>>> s_badbaduser = """
... (lambda fc=(
... lambda n: [
... c for c in
... ().__class__.__bases__[0].__subclasses__()
... if c.__name__ == n
... ][0]
... ):
... fc("function")(
... fc("code")(
... 0,0,0,0,"KABOOM",(),(),(),"","",0,""
... ),{}
... )()
... )()
... """
>>> eval(s_badbaduser, {"__builtins__":None}, safe_dict)
Segmentation fault
Кроме того, использование eval
для синтаксического анализа и оценки математических выражений кажется мне неправильным.
Я нашел PyMathParser, но он также использует eval
под капотом и не лучше:
>>> import MathParser
>>> m=MathParser.PyMathParser()
>>> m.expression = s_badbaduser
>>> m.evaluate();
Segmentation fault
Имеется ли библиотека, которая будет анализировать и оценивать математическое выражение без использования парсера Python?