Skip to content

Commit

Permalink
added function and class to import parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Maas committed Sep 6, 2022
1 parent 1d58a26 commit 592d0cb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion deptry/import_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

from deptry.notebook_import_extractor import NotebookImportExtractor

RECURSION_TYPES = [ast.If, ast.Try, ast.ExceptHandler, ast.FunctionDef, ast.ClassDef]


class ImportParser:
"""
Expand Down Expand Up @@ -57,9 +59,10 @@ def _get_import_nodes_from(self, root: Union[ast.Module, ast.If]):
are defined within if/else or try/except statements. In that case, the ast.Import or ast.ImportFrom node
is a child of an ast.If/Try/ExceptHandler node.
"""

imports = []
for node in ast.iter_child_nodes(root):
if isinstance(node, ast.If) or isinstance(node, ast.Try) or isinstance(node, ast.ExceptHandler):
if any([isinstance(node, recursion_type) for recursion_type in RECURSION_TYPES]):
imports += self._get_import_nodes_from(node)
elif isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
imports += [node]
Expand Down
25 changes: 25 additions & 0 deletions tests/test_import_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,28 @@ def test_import_parser_tryexcept():
"""
)
assert set(imported_modules) == set(["numpy", "pandas", "click", "logging"])


def test_import_parser_func():
imported_modules = ImportParser().get_imported_modules_from_str(
"""
import pandas as pd
from numpy import random
def func():
import click
"""
)
assert set(imported_modules) == set(["numpy", "pandas", "click"])


def test_import_parser_class():
imported_modules = ImportParser().get_imported_modules_from_str(
"""
import pandas as pd
from numpy import random
class MyClass:
def __init__(self):
import click
"""
)
assert set(imported_modules) == set(["numpy", "pandas", "click"])

0 comments on commit 592d0cb

Please sign in to comment.