Skip to content

Commit 55e5558

Browse files
committed
Enhance ImportAnalyzer to accurately classify imports
This commit improves the ImportAnalyzer class by refining the logic for classifying imports as "third_party" or "local". It introduces checks to ensure that modules found in site-packages are correctly identified as third-party, even if they are resolved as local imports. Additionally, it streamlines the import classification process by removing redundant checks, enhancing the overall accuracy and efficiency of the import analysis.
1 parent a41a465 commit 55e5558

1 file changed

Lines changed: 16 additions & 5 deletions

File tree

src/python_package_folder/analyzer.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -227,21 +227,29 @@ def classify_import(self, import_info: ImportInfo, src_dir: Path) -> None:
227227
import_info.classification = "stdlib"
228228
return
229229

230+
# Check if it's a third-party package (in site-packages) FIRST
231+
# This must be checked before resolve_local_import to avoid incorrectly
232+
# classifying site-packages modules as "external" when they're found
233+
# by the recursive search
234+
if self.is_third_party(module_name):
235+
import_info.classification = "third_party"
236+
return
237+
230238
# Try to resolve as a local import
231239
resolved = self.resolve_local_import(import_info, src_dir)
232240
if resolved is not None:
241+
# Double-check: if resolved path is in site-packages, it's actually third-party
242+
# (this can happen if the recursive search finds it before importlib does)
243+
if "site-packages" in str(resolved) or "dist-packages" in str(resolved):
244+
import_info.classification = "third_party"
245+
return
233246
if resolved.is_relative_to(src_dir):
234247
import_info.classification = "local"
235248
else:
236249
import_info.classification = "external"
237250
import_info.resolved_path = resolved
238251
return
239252

240-
# Check if it's a third-party package (in site-packages)
241-
if self.is_third_party(module_name):
242-
import_info.classification = "third_party"
243-
return
244-
245253
# Mark as ambiguous if we can't determine
246254
import_info.classification = "ambiguous"
247255

@@ -341,6 +349,9 @@ def resolve_local_import(self, import_info: ImportInfo, src_dir: Path) -> Path |
341349
# Only search within project_root to avoid going too far
342350
if not potential_file.is_relative_to(self.project_root):
343351
continue
352+
# Skip site-packages and dist-packages (these are third-party, not external)
353+
if "site-packages" in str(potential_file) or "dist-packages" in str(potential_file):
354+
continue
344355
# Skip excluded patterns
345356
if any(
346357
part.startswith("_SS")

0 commit comments

Comments
 (0)