Merge pull request #4929 from nothariharan/fix/python-pep420-src-namespace
fix(python): resolve imports across PEP 420 namespace packages under src/
This commit is contained in:
2 files changed
+102
-2
No files matched your search
+28
-2
@@ -453,6 +453,23 @@ def _suppress_ambiguous_python_imports(
|
||||
raw_call["_ambiguous_python_import"] = True
|
||||
|
||||
|
||||
def _namespace_src_module_parts(parts: tuple[str, ...]) -> tuple[str, ...] | None:
|
||||
"""Module path of a file in a PEP 420 namespace package under a `src/` root.
|
||||
|
||||
`parts` is the file's path relative to the scan root. Returns the parts after
|
||||
the nearest `src` directory when the module sits at least one directory below
|
||||
it (`airflow/sql/hooks/sql.py`), else None. A loose `src/helpers.py` is left
|
||||
alone: its bare name is as likely a third-party import. So is a namespace
|
||||
named like a stdlib module, which a bare import means first (#4261)."""
|
||||
dirs = parts[:-1]
|
||||
if "src" not in dirs:
|
||||
return None
|
||||
after = parts[len(dirs) - dirs[::-1].index("src"):]
|
||||
if len(after) < 2 or after[0] in _PYTHON_STDLIB_MODULE_NAMES:
|
||||
return None
|
||||
return after
|
||||
|
||||
|
||||
def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
|
||||
"""Repoint Python absolute-import edges to the real file node under a nested
|
||||
(e.g. ``src/``) package root (#2072).
|
||||
@@ -492,8 +509,17 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
|
||||
levels += 1
|
||||
d = d.parent
|
||||
if levels == 0:
|
||||
continue # not inside a package (namespace pkg / loose module)
|
||||
mod_parts = parts[-(levels + 1):] # package dirs + the file itself
|
||||
# No initializer above the file: a PEP 420 namespace package, or a
|
||||
# loose module. Under a `src/` layout the import root is that `src/`,
|
||||
# so `pkgsql/src/airflow/sql/hooks/sql.py` is `airflow.sql.hooks.sql`
|
||||
# even though no directory carries an `__init__.py`. Without this a
|
||||
# monorepo of namespace distributions dropped every cross-distribution
|
||||
# import, and with it inherited `self.method()` calls.
|
||||
mod_parts = _namespace_src_module_parts(parts)
|
||||
if mod_parts is None:
|
||||
continue # loose module, not under a src/ root
|
||||
else:
|
||||
mod_parts = parts[-(levels + 1):] # package dirs + the file itself
|
||||
if len(mod_parts) == len(parts):
|
||||
continue # package root == scan root: file-node id already coincides
|
||||
file_node = _file_node_id(rel)
|
||||
|
||||
@@ -365,3 +365,77 @@ def test_non_python_import_edge_is_not_repointed(tmp_path):
|
||||
assert not any(v == "src_pkg_mod" and u == "app_cs" for _, u, v in _import_edges(G)), (
|
||||
"non-Python import edge was repointed onto a Python file (#2072 review)"
|
||||
)
|
||||
|
||||
|
||||
def _write_tree(base: Path, files: dict[str, str]) -> list[Path]:
|
||||
written = []
|
||||
for rel, body in files.items():
|
||||
p = base / rel
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(body, encoding="utf-8")
|
||||
written.append(p)
|
||||
return written
|
||||
|
||||
|
||||
_NAMESPACE_BASE = (
|
||||
"class DbApiHook:\n"
|
||||
" def strip_sql_string(self, sql):\n"
|
||||
" return sql\n\n"
|
||||
"def free_fn():\n"
|
||||
" return 1\n"
|
||||
)
|
||||
_NAMESPACE_SUB = (
|
||||
"from airflow.sql.hooks.sql import DbApiHook, free_fn\n\n"
|
||||
"class PrestoHook(DbApiHook):\n"
|
||||
" def get_records(self, sql):\n"
|
||||
" free_fn()\n"
|
||||
" return self.strip_sql_string(sql)\n"
|
||||
)
|
||||
|
||||
|
||||
def _calls(result) -> set[tuple[str, str, str]]:
|
||||
labels = {n["id"]: n.get("label", n["id"]) for n in result["nodes"]}
|
||||
return {
|
||||
(labels.get(e["source"], e["source"]), labels.get(e["target"], e["target"]), e.get("confidence"))
|
||||
for e in result["edges"] if e.get("relation") == "calls"
|
||||
}
|
||||
|
||||
|
||||
def test_namespace_distributions_under_src_resolve_across_each_other(tmp_path):
|
||||
"""PEP 420: two distributions share the `airflow` namespace, each under its
|
||||
own `src/`, and no directory has an `__init__.py`. The import across them
|
||||
resolves, so the subclass's inherited `self.strip_sql_string()` call and the
|
||||
imported `free_fn()` are extracted, not dropped or left as name guesses."""
|
||||
paths = _write_tree(tmp_path, {
|
||||
"pkgsql/src/airflow/sql/hooks/sql.py": _NAMESPACE_BASE,
|
||||
"pkgpresto/src/airflow/presto/hooks/presto.py": _NAMESPACE_SUB,
|
||||
})
|
||||
calls = _calls(extract(paths, cache_root=tmp_path / "c", root=tmp_path, parallel=False))
|
||||
assert (".get_records()", ".strip_sql_string()", "EXTRACTED") in calls, calls
|
||||
assert (".get_records()", "free_fn()", "EXTRACTED") in calls, calls
|
||||
|
||||
|
||||
def test_namespace_module_under_two_src_roots_stays_unresolved(tmp_path):
|
||||
"""The same namespace module under two `src/` roots is ambiguous: no call is
|
||||
bound to either copy."""
|
||||
paths = _write_tree(tmp_path, {
|
||||
"a/src/airflow/sql/hooks/sql.py": _NAMESPACE_BASE,
|
||||
"b/src/airflow/sql/hooks/sql.py": _NAMESPACE_BASE,
|
||||
"c/src/airflow/presto/hooks/presto.py": _NAMESPACE_SUB,
|
||||
})
|
||||
calls = _calls(extract(paths, cache_root=tmp_path / "c", root=tmp_path, parallel=False))
|
||||
assert not any(t == ".strip_sql_string()" for _, t, _ in calls), calls
|
||||
assert not any(t == "free_fn()" and c == "EXTRACTED" for _, t, c in calls), calls
|
||||
|
||||
|
||||
def test_loose_module_directly_under_src_is_not_aliased(tmp_path):
|
||||
"""`src/helpers.py` (no namespace dir) keeps its old handling: a bare
|
||||
`import helpers` elsewhere may name a third-party module."""
|
||||
from graphify.extract import _namespace_src_module_parts
|
||||
|
||||
assert _namespace_src_module_parts(("pkg", "src", "helpers.py")) is None
|
||||
assert _namespace_src_module_parts(("pkg", "src", "logging", "handlers.py")) is None
|
||||
assert _namespace_src_module_parts(("scripts", "tool.py")) is None
|
||||
assert _namespace_src_module_parts(("d", "src", "airflow", "sql", "hooks", "sql.py")) == (
|
||||
"airflow", "sql", "hooks", "sql.py",
|
||||
)
|
||||
Reference in new issue
Block a user