ast.literal_eval
(位于ast.py
_ ast.parse
不幸的是,代码根本无法扩展,因此要添加Decimal
到代码中,您需要复制所有代码并重新开始。
对于更简单的方法,您可以使用ast.parse
module 来解析表达式,然后使用ast.NodeVisitor
orast.NodeTransformer
来确保没有不需要的语法或不需要的变量访问。compile
然后用and编译eval
得到结果。
literal_eval
该代码与该代码实际使用的代码略有不同eval
,但在我看来更容易理解,并且不需要深入挖掘 AST 树。它专门只允许某些语法,明确禁止例如 lambdas、属性访问(foo.__dict__
非常邪恶)或访问任何被认为不安全的名称。它可以很好地解析您的表达式,并且作为额外的我还添加了Num
(浮点数和整数)、列表和字典文字。
此外,在 2.7 和 3.3 上的工作方式相同
import ast
import decimal
source = "(Decimal('11.66985'), Decimal('1e-8'),"\
"(1,), (1,2,3), 1.2, [1,2,3], {1:2})"
tree = ast.parse(source, mode='eval')
# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
ALLOWED_NODE_TYPES = set([
'Expression', # a top node for an expression
'Tuple', # makes a tuple
'Call', # a function call (hint, Decimal())
'Name', # an identifier...
'Load', # loads a value of a variable with given identifier
'Str', # a string literal
'Num', # allow numbers too
'List', # and list literals
'Dict', # and dicts...
])
def visit_Name(self, node):
if not node.id in self.ALLOWED_NAMES:
raise RuntimeError("Name access to %s is not allowed" % node.id)
# traverse to child nodes
return self.generic_visit(node)
def generic_visit(self, node):
nodetype = type(node).__name__
if nodetype not in self.ALLOWED_NODE_TYPES:
raise RuntimeError("Invalid expression: %s not allowed" % nodetype)
return ast.NodeTransformer.generic_visit(self, node)
transformer = Transformer()
# raises RuntimeError on invalid code
transformer.visit(tree)
# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')
# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))
print(result)