Used by `literal_eval` to convert an AST node into a value.
(node)
| 65 | |
| 66 | |
| 67 | def _convert_literal(node): |
| 68 | """ |
| 69 | Used by `literal_eval` to convert an AST node into a value. |
| 70 | """ |
| 71 | if isinstance(node, Constant): |
| 72 | return node.value |
| 73 | if isinstance(node, Dict) and len(node.keys) == len(node.values): |
| 74 | return dict(zip( |
| 75 | map(_convert_literal, node.keys), |
| 76 | map(_convert_literal, node.values), |
| 77 | )) |
| 78 | if isinstance(node, Tuple): |
| 79 | return tuple(map(_convert_literal, node.elts)) |
| 80 | if isinstance(node, List): |
| 81 | return list(map(_convert_literal, node.elts)) |
| 82 | if isinstance(node, Set): |
| 83 | return set(map(_convert_literal, node.elts)) |
| 84 | if ( |
| 85 | isinstance(node, Call) and isinstance(node.func, Name) |
| 86 | and node.func.id == 'set' and node.args == node.keywords == [] |
| 87 | ): |
| 88 | return set() |
| 89 | if ( |
| 90 | isinstance(node, UnaryOp) |
| 91 | and isinstance(node.op, (UAdd, USub)) |
| 92 | and isinstance(node.operand, Constant) |
| 93 | and type(operand := node.operand.value) in (int, float, complex) |
| 94 | ): |
| 95 | if isinstance(node.op, UAdd): |
| 96 | return + operand |
| 97 | else: |
| 98 | return - operand |
| 99 | if ( |
| 100 | isinstance(node, BinOp) |
| 101 | and isinstance(node.op, (Add, Sub)) |
| 102 | and isinstance(node.left, (Constant, UnaryOp)) |
| 103 | and isinstance(node.right, Constant) |
| 104 | and type(left := _convert_literal(node.left)) in (int, float) |
| 105 | and type(right := _convert_literal(node.right)) is complex |
| 106 | ): |
| 107 | if isinstance(node.op, Add): |
| 108 | return left + right |
| 109 | else: |
| 110 | return left - right |
| 111 | msg = "malformed node or string" |
| 112 | if lno := getattr(node, 'lineno', None): |
| 113 | msg += f' on line {lno}' |
| 114 | raise ValueError(msg + f': {node!r}') |
| 115 | |
| 116 | |
| 117 | def dump( |
no test coverage detected
searching dependent graphs…