Safe way to parse user-supplied mathematical formula in Python

后端 未结 3 1915
忘了有多久
忘了有多久 2020-11-30 03:11

Is there a math expressions parser + evaluator for Python?

I am not the first to ask this question, but answers usually point to eval(). For instance,

3条回答
  •  时光取名叫无心
    2020-11-30 03:58

    I'd suggest using ast.parse and then whitelisting the parse tree.

    tree = ast.parse(s, mode='eval')
    valid = all(isinstance(node, whitelist) for node in ast.walk(tree))
    if valid:
        result = eval(compile(tree, filename='', mode='eval'),
                      {"__builtins__": None}, safe_dict)
    

    Here whitelist could be something like:

    whitelist = (ast.Expression, ast.Call, ast.Name, ast.Load,
                 ast.BinOp, ast.UnaryOp, ast.operator, ast.unaryop, ast.cmpop,
                 ast.Num,
                )
    

提交回复
热议问题