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

Function touch_import

tools/python-3.11.9-amd64/Lib/lib2to3/fixer_util.py:315–357  ·  view source on GitHub ↗

Works like `does_tree_import` but adds an import statement if it was not imported.

(package, name, node)

Source from the content-addressed store, hash-verified

313 return node.type in (syms.import_name, syms.import_from)
314
315def touch_import(package, name, node):
316 """ Works like `does_tree_import` but adds an import statement
317 if it was not imported. """
318 def is_import_stmt(node):
319 return (node.type == syms.simple_stmt and node.children and
320 is_import(node.children[0]))
321
322 root = find_root(node)
323
324 if does_tree_import(package, name, root):
325 return
326
327 # figure out where to insert the new import. First try to find
328 # the first import and then skip to the last one.
329 insert_pos = offset = 0
330 for idx, node in enumerate(root.children):
331 if not is_import_stmt(node):
332 continue
333 for offset, node2 in enumerate(root.children[idx:]):
334 if not is_import_stmt(node2):
335 break
336 insert_pos = idx + offset
337 break
338
339 # if there are no imports where we can insert, find the docstring.
340 # if that also fails, we stick to the beginning of the file
341 if insert_pos == 0:
342 for idx, node in enumerate(root.children):
343 if (node.type == syms.simple_stmt and node.children and
344 node.children[0].type == token.STRING):
345 insert_pos = idx + 1
346 break
347
348 if package is None:
349 import_ = Node(syms.import_name, [
350 Leaf(token.NAME, "import"),
351 Leaf(token.NAME, name, prefix=" ")
352 ])
353 else:
354 import_ = FromImport(package, [Leaf(token.NAME, name, prefix=" ")])
355
356 children = [import_, Newline()]
357 root.insert_child(insert_pos, Node(syms.simple_stmt, children))
358
359
360_def_syms = {syms.classdef, syms.funcdef}

Callers 4

transformMethod · 0.90
_handle_type2abcMethod · 0.90
transformMethod · 0.85
transformMethod · 0.85

Calls 9

find_rootFunction · 0.85
does_tree_importFunction · 0.85
enumerateFunction · 0.85
is_import_stmtFunction · 0.85
LeafClass · 0.85
FromImportFunction · 0.85
NewlineFunction · 0.85
insert_childMethod · 0.80
NodeClass · 0.70

Tested by

no test coverage detected