Lines Matching full:node
33 Parse the source into an AST node.
53 Safely evaluate an expression node or a string containing a Python
54 expression. The string or node provided may only consist of the following
62 def _raise_malformed_node(node): argument
63 raise ValueError(f'malformed node or string: {node!r}')
64 def _convert_num(node): argument
65 if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
66 _raise_malformed_node(node)
67 return node.value
68 def _convert_signed_num(node): argument
69 if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
70 operand = _convert_num(node.operand)
71 if isinstance(node.op, UAdd):
75 return _convert_num(node)
76 def _convert(node): argument
77 if isinstance(node, Constant):
78 return node.value
79 elif isinstance(node, Tuple):
80 return tuple(map(_convert, node.elts))
81 elif isinstance(node, List):
82 return list(map(_convert, node.elts))
83 elif isinstance(node, Set):
84 return set(map(_convert, node.elts))
85 elif isinstance(node, Dict):
86 if len(node.keys) != len(node.values):
87 _raise_malformed_node(node)
88 return dict(zip(map(_convert, node.keys),
89 map(_convert, node.values)))
90 elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
91 left = _convert_signed_num(node.left)
92 right = _convert_num(node.right)
94 if isinstance(node.op, Add):
98 return _convert_signed_num(node)
102 def dump(node, annotate_fields=True, include_attributes=False): argument
104 Return a formatted dump of the tree in node. This is mainly useful for
112 def _format(node): argument
113 if isinstance(node, AST):
116 for field in node._fields:
118 value = getattr(node, field)
126 if include_attributes and node._attributes:
127 for a in node._attributes:
129 args.append('%s=%s' % (a, _format(getattr(node, a))))
132 return '%s(%s)' % (node.__class__.__name__, ', '.join(args))
133 elif isinstance(node, list):
134 return '[%s]' % ', '.join(_format(x) for x in node)
135 return repr(node)
136 if not isinstance(node, AST):
137 raise TypeError('expected AST, got %r' % node.__class__.__name__)
138 return _format(node)
153 def fix_missing_locations(node): argument
155 When you compile a node tree with compile(), the compiler expects lineno and
156 col_offset attributes for every node that supports them. This is rather
159 parent node. It works recursively starting at *node*.
161 def _fix(node, lineno, col_offset, end_lineno, end_col_offset): argument
162 if 'lineno' in node._attributes:
163 if not hasattr(node, 'lineno'):
164 node.lineno = lineno
166 lineno = node.lineno
167 if 'end_lineno' in node._attributes:
168 if not hasattr(node, 'end_lineno'):
169 node.end_lineno = end_lineno
171 end_lineno = node.end_lineno
172 if 'col_offset' in node._attributes:
173 if not hasattr(node, 'col_offset'):
174 node.col_offset = col_offset
176 col_offset = node.col_offset
177 if 'end_col_offset' in node._attributes:
178 if not hasattr(node, 'end_col_offset'):
179 node.end_col_offset = end_col_offset
181 end_col_offset = node.end_col_offset
182 for child in iter_child_nodes(node):
184 _fix(node, 1, 0, 1, 0)
185 return node
188 def increment_lineno(node, n=1): argument
190 Increment the line number and end line number of each node in the tree
191 starting at *node* by *n*. This is useful to "move code" to a different
194 for child in walk(node):
199 return node
202 def iter_fields(node): argument
204 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
205 that is present on *node*.
207 for field in node._fields:
209 yield field, getattr(node, field)
214 def iter_child_nodes(node): argument
216 Yield all direct child nodes of *node*, that is, all fields that are nodes
219 for name, field in iter_fields(node):
228 def get_docstring(node, clean=True): argument
230 Return the docstring for the given node or None if no docstring can
231 be found. If the node provided does not have docstrings a TypeError
237 if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
238 raise TypeError("%r can't have docstrings" % node.__class__.__name__)
239 if not(node.body and isinstance(node.body[0], Expr)):
241 node = node.body[0].value
242 if isinstance(node, Str):
243 text = node.s
244 elif isinstance(node, Constant) and isinstance(node.value, str):
245 text = node.value
290 def get_source_segment(source, node, *, padded=False): argument
291 """Get source code segment of the *source* that generated *node*.
300 lineno = node.lineno - 1
301 end_lineno = node.end_lineno - 1
302 col_offset = node.col_offset
303 end_col_offset = node.end_col_offset
325 def walk(node): argument
327 Recursively yield all descendant nodes in the tree starting at *node*
328 (including *node* itself), in no specified order. This is useful if you
332 todo = deque([node])
334 node = todo.popleft()
335 todo.extend(iter_child_nodes(node))
336 yield node
341 A node visitor base class that walks the abstract syntax tree and calls a
342 visitor function for every node found. This function may return a value
349 class name of the node. So a `TryFinally` node visit function would
351 the `visit` method. If no visitor function exists for a node
359 def visit(self, node): argument
360 """Visit a node."""
361 method = 'visit_' + node.__class__.__name__
363 return visitor(node)
365 def generic_visit(self, node): argument
366 """Called if no explicit visitor function exists for a node."""
367 for field, value in iter_fields(node):
375 def visit_Constant(self, node): argument
376 value = node.value
393 return visitor(node)
394 return self.generic_visit(node)
403 visitor methods to replace or remove the old node. If the return value of
404 the visitor method is ``None``, the node will be removed from its location,
406 original node in which case no replacement takes place.
413 def visit_Name(self, node):
416 slice=Index(value=Str(s=node.id)),
417 ctx=node.ctx
420 Keep in mind that if the node you're operating on has child nodes you must
422 method for the node first.
426 just a single node.
430 node = YourTransformer().visit(node)
433 def generic_visit(self, node): argument
434 for field, old_value in iter_fields(node):
450 delattr(node, field)
452 setattr(node, field, new_node)
453 return node