Skip to content

Commit

Permalink
solved issue with importing from local files (#163)
Browse files Browse the repository at this point in the history
* solved issue with importing from files in same directory begin marked as missing dependencies
  • Loading branch information
fpgmaas authored Oct 22, 2022
1 parent 7659a91 commit 0c42bd0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
28 changes: 27 additions & 1 deletion deptry/import_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
class ImportParser:
"""
Class to scan Python files or Python code for import statements. Scanning is done by creating the abstract syntax tree
and extracting all nodes that contain import statements.
and extracting all nodes that contain import statements. For each file, imports from files in the same directory as the file that is being
scanned are excluded.
"""

def __init__(self) -> None:
Expand All @@ -29,6 +30,7 @@ def get_imported_modules_for_list_of_files(self, list_of_files: List[Path]) -> L
return unique_modules

def get_imported_modules_from_file(self, path_to_file: Path) -> List[str]:
logging.debug(f"Scanning {path_to_file}...")
try:
if str(path_to_file).endswith(".ipynb"):
modules = self._get_imported_modules_from_ipynb(path_to_file)
Expand All @@ -39,6 +41,7 @@ def get_imported_modules_from_file(self, path_to_file: Path) -> List[str]:
except AttributeError as e:
logging.warning(f"Warning: Parsing imports for file {str(path_to_file)} failed.")
raise (e)
modules = self._remove_local_file_imports(modules, path_to_file)
return modules

def get_imported_modules_from_str(self, file_str: str) -> List[str]:
Expand Down Expand Up @@ -122,3 +125,26 @@ def _filter_exceptions(modules: List[str]) -> List[str]:
def _get_file_encoding(file_name: Union[str, Path]) -> str:
with open(file_name, "rb") as f:
return chardet.detect(f.read())["encoding"]

@staticmethod
def _remove_local_file_imports(modules: List[str], path_to_file: Path) -> List[str]:
"""
This omits imported modules from .py files in the same directory from the list of modules. consider the following directory:
dir
- foo.py
- bar.py
In this case, if foo.py any imports from bar.py such as 'from bar import x', we do not want 'bar'
to be included in the list of module that foo imports from.
"""
current_directory = path_to_file.parent
py_files_in_same_dir = [p.stem for p in current_directory.iterdir() if p.is_file() and p.suffix == ".py"]
local_files_imported = list(set(modules) & set(py_files_in_same_dir))
if len(local_files_imported) > 0:
logging.debug(
f"Imports {local_files_imported} found to be imports from local .py files. Removing them from the list"
" of imported modules."
)
return [module for module in modules if module not in py_files_in_same_dir]
return modules
11 changes: 11 additions & 0 deletions tests/test_import_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,17 @@ def test_import_parser_file_encodings(tmp_path):
assert set(imported_modules) == {"foo"}


def test_remove_local_file_imports(tmp_path):
with run_within_dir(tmp_path):
with open("foo.py", "w", encoding="utf-8") as f:
f.write("import hobbes\nimport bar\nfrom bar import x")
with open("bar.py", "w", encoding="utf-8") as f:
f.write("def x():\tprint('hello')")

imported_modules = ImportParser().get_imported_modules_from_file(Path("foo.py"))
assert imported_modules == ["hobbes"]


def test_import_parser_file_encodings_warning(tmp_path, caplog):
with run_within_dir(tmp_path):
with open("file1.py", "w", encoding="utf-8") as f:
Expand Down

0 comments on commit 0c42bd0

Please sign in to comment.