Skip to content

Python Imports

python_imports

Walk a Python package's init.py import chain.

Odoo only loads Python files that are explicitly imported through the package's init.py chain. This module resolves that set so callers can mirror Odoo's loading semantics rather than what's on disk.

Functions:

Name Description
discover_imported_files

Return absolute paths of .py files reachable from package_dir/__init__.py.

discover_imported_files

discover_imported_files(package_dir: Path) -> list[Path]

Return absolute paths of .py files reachable from package_dir/__init__.py.

Follows from . import name and from .name import … statements recursively. A name resolves to name.py when that file exists, or to name/ when that subdirectory contains an __init__.py (recursing into it). Names that resolve to neither are skipped with a debug log line.

Returns an empty list when package_dir does not exist or contains no __init__.py. Files are returned in deterministic (depth-first, declaration) order; duplicates are de-duplicated.

Parameters:

Name Type Description Default

package_dir

Path

Directory expected to contain an __init__.py.

required

Returns:

Type Description
list[Path]

Absolute, resolved Path objects pointing to the imported

list[Path]

.py files (excluding __init__.py files themselves).

Source code in src/oops/io/python_imports.py
def discover_imported_files(package_dir: Path) -> list[Path]:
    """Return absolute paths of .py files reachable from ``package_dir/__init__.py``.

    Follows ``from . import name`` and ``from .name import …`` statements
    recursively. A name resolves to ``name.py`` when that file exists, or
    to ``name/`` when that subdirectory contains an ``__init__.py``
    (recursing into it). Names that resolve to neither are skipped with
    a debug log line.

    Returns an empty list when ``package_dir`` does not exist or contains
    no ``__init__.py``. Files are returned in deterministic (depth-first,
    declaration) order; duplicates are de-duplicated.

    Args:
        package_dir: Directory expected to contain an ``__init__.py``.

    Returns:
        Absolute, resolved ``Path`` objects pointing to the imported
        ``.py`` files (excluding ``__init__.py`` files themselves).
    """
    if not package_dir.is_dir():
        return []
    init_path = package_dir / "__init__.py"
    if not init_path.is_file():
        return []
    seen: set[Path] = set()
    out: list[Path] = []
    _walk(package_dir, seen, out)
    return out