From 37c1d10f1a41c0db3d1ea09a95bd00448f874ff7 Mon Sep 17 00:00:00 2001 From: Andreas Gattringer <andreas.gattringer@univie.ac.at> Date: Thu, 28 Mar 2024 14:50:50 +0100 Subject: [PATCH] imports: also handle imports in top-level try...except blocks --- scripts/helpers/imports.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/scripts/helpers/imports.py b/scripts/helpers/imports.py index ac949d2..042d01e 100644 --- a/scripts/helpers/imports.py +++ b/scripts/helpers/imports.py @@ -7,6 +7,25 @@ def get_module_names(node: ast.Import): return names +def import_names(node): + result = [] + if isinstance(node, ast.Import): + print("\t", ",".join(get_module_names(node))) + result.extend(get_module_names(node)) + elif isinstance(node, ast.ImportFrom): + print("\t", node.module) + result.append(node.module) + + if isinstance(node, ast.Try): + for child in ast.iter_child_nodes(node): + result.extend(import_names(child)) + for handler in node.handlers: + for child in ast.iter_child_nodes(handler): + result.extend(import_names(child)) + + return result + + def get_imported_files( fn, modules=None, @@ -22,12 +41,10 @@ def get_imported_files( current_modules = [] with open(fn) as f: + print(f"Reading {fn}") root = ast.parse(f.read(), fn) for node in ast.iter_child_nodes(root): - if isinstance(node, ast.Import): - current_modules.extend(get_module_names(node)) - elif isinstance(node, ast.ImportFrom): - current_modules.append(node.module) + current_modules.extend(import_names(node)) current_modules = sorted(list(set(current_modules))) for module in current_modules: -- GitLab