I have a class (based on this answer) that uses ast.NodeVisitor
to get a list of modules imported by a Python file. However, I also want to return the line and column offsets for where the module names are located in the file.
Code:
import ast
class ImportFinder(ast.NodeVisitor):
def __init__(self):
self.imports = []
def visit_Import(self, node):
for i in node.names:
self.imports.append({'import_type': "import", 'module': i.name,})
def visit_ImportFrom(self, node):
self.imports.append({'import_type': "from", 'module': node.module})
def parse_imports(source):
tree = ast.parse(source)
finder = ImportFinder()
finder.visit(tree)
return finder.imports
# Example usage
sample_file = '''
from foo import bar, baz, frob
import bar.baz
import bar.foo as baf
'''
parsed_imports = parse_imports(sample_file)
for i in parsed_imports:
print(i)
Current output:
{'import_type': 'from', 'module': 'foo'}
{'import_type': 'import', 'module': 'bar.baz'}
{'import_type': 'import', 'module': 'bar.foo'}
Desired output:
{'import_type': 'from', 'module': 'foo', 'line': 2, 'column_offset': 5}
{'import_type': 'import', 'module': 'bar.baz', 'line': 3, 'column_offset': 7}
{'import_type': 'import', 'module': 'bar.foo', 'line': 4, 'column_offset': 9}
How do I get the line and column offsets for imported Python module names?