Skip to content

Commit

Permalink
fix: Fix visiting relative imports in non-init modules
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Sep 28, 2023
1 parent 49c9bdc commit c1138c3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/griffe/agents/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,8 +522,8 @@ def visit_importfrom(self, node: ast.ImportFrom) -> None:
node: The node to visit.
"""
for name in node.names:
if not node.module and node.level == 1 and not name.asname:
# special case: when being in `a` and doing `from . import b`,
if not node.module and node.level == 1 and not name.asname and self.current.module.is_init_module:
# special case: when being in `a/__init__.py` and doing `from . import b`,
# we are effectively creating a member `b` in `a` that is pointing to `a.b`
# -> cyclic alias! in that case, we just skip it, as both the member and module
# have the same name and can be accessed the same way
Expand Down
2 changes: 2 additions & 0 deletions tests/test_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@
("code", "path", "is_package", "expected"),
[
("from . import b", "a", False, "a.b"),
("from . import b", "a", True, "a.b"),
("from . import c", "a.b", False, "a.c"),
("from . import c", "a.b", True, "a.b.c"),
("from . import d", "a.b.c", False, "a.b.d"),
("from .c import d", "a", False, "a.c.d"),
("from .c import d", "a.b", False, "a.c.d"),
Expand Down
17 changes: 16 additions & 1 deletion tests/test_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pytest

from griffe.loader import GriffeLoader
from griffe.tests import temporary_pypackage, temporary_visited_module
from griffe.tests import temporary_pypackage, temporary_visited_module, temporary_visited_package

# @given(hs.from_node(node=libcst.Module))
# @pytest.mark.skipif(sys.version_info >= (3, 11, 0), reason="Too slow on Python 3.11?")
Expand Down Expand Up @@ -352,3 +352,18 @@ class B:
""",
) as module:
assert module["A.B"].runtime


def test_visiting_relative_imports_triggering_cyclic_aliases() -> None:
"""Skip specific imports to avoid cyclic aliases."""
with temporary_visited_package(
"pkg",
{
"__init__.py": "from . import a",
"a.py": "from . import b",
"b.py": "",
},
) as pkg:
assert "a" not in pkg.imports
assert "b" in pkg["a"].imports
assert pkg["a"].imports["b"] == "pkg.b"

0 comments on commit c1138c3

Please sign in to comment.