MCPcopy Create free account
hub / github.com/RT-Thread/env-windows / literal_eval

Function literal_eval

tools/python-3.11.9-amd64/Lib/ast.py:54–110  ·  view source on GitHub ↗

Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. Caution: A complex expression ca

(node_or_string)

Source from the content-addressed store, hash-verified

52
53
54def literal_eval(node_or_string):
55 """
56 Evaluate an expression node or a string containing only a Python
57 expression. The string or node provided may only consist of the following
58 Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
59 sets, booleans, and None.
60
61 Caution: A complex expression can overflow the C stack and cause a crash.
62 """
63 if isinstance(node_or_string, str):
64 node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
65 if isinstance(node_or_string, Expression):
66 node_or_string = node_or_string.body
67 def _raise_malformed_node(node):
68 msg = "malformed node or string"
69 if lno := getattr(node, 'lineno', None):
70 msg += f' on line {lno}'
71 raise ValueError(msg + f': {node!r}')
72 def _convert_num(node):
73 if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
74 _raise_malformed_node(node)
75 return node.value
76 def _convert_signed_num(node):
77 if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
78 operand = _convert_num(node.operand)
79 if isinstance(node.op, UAdd):
80 return + operand
81 else:
82 return - operand
83 return _convert_num(node)
84 def _convert(node):
85 if isinstance(node, Constant):
86 return node.value
87 elif isinstance(node, Tuple):
88 return tuple(map(_convert, node.elts))
89 elif isinstance(node, List):
90 return list(map(_convert, node.elts))
91 elif isinstance(node, Set):
92 return set(map(_convert, node.elts))
93 elif (isinstance(node, Call) and isinstance(node.func, Name) and
94 node.func.id == 'set' and node.args == node.keywords == []):
95 return set()
96 elif isinstance(node, Dict):
97 if len(node.keys) != len(node.values):
98 _raise_malformed_node(node)
99 return dict(zip(map(_convert, node.keys),
100 map(_convert, node.values)))
101 elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
102 left = _convert_signed_num(node.left)
103 right = _convert_num(node.right)
104 if isinstance(left, (int, float)) and isinstance(right, complex):
105 if isinstance(node.op, Add):
106 return left + right
107 else:
108 return left - right
109 return _convert_signed_num(node)
110 return _convert(node_or_string)
111

Callers 1

renderFunction · 0.90

Calls 3

lstripMethod · 0.80
parseFunction · 0.70
_convertFunction · 0.70

Tested by

no test coverage detected