FoundationAgents/MetaGPT · error · ValueError

Failed to import module __init__ with error:No module named

Error message

Failed to import module __init__ with error:No module named __init__.

What it means

RepoParser.generate_class_views (pyreverse-based class diagram generation) requires an __init__.py in the target directory to treat it as an importable package; if missing, this ValueError is raised mimicking an import failure. The check runs before invoking the pyreverse subprocess.

Source

Thrown at metagpt/repo_parser.py:727

            None or Parsed information from the assignment node.
        """
        return [RepoParser._parse_variable(t) for t in node.targets]

    async def rebuild_class_views(self, path: str | Path = None):
        """
        Executes `pylint` to reconstruct the dot format class view repository file.

        Args:
            path (str | Path): The path to the target directory or file. Default is None.
        """
        if not path:
            path = self.base_directory
        path = Path(path)
        if not path.exists():
            return
        init_file = path / "__init__.py"
        if not init_file.exists():
            raise ValueError("Failed to import module __init__ with error:No module named __init__.")
        command = f"pyreverse {str(path)} -o dot"
        output_dir = path / "__dot__"
        output_dir.mkdir(parents=True, exist_ok=True)
        result = subprocess.run(command, shell=True, check=True, cwd=str(output_dir))
        if result.returncode != 0:
            raise ValueError(f"{result}")
        class_view_pathname = output_dir / "classes.dot"
        class_views = await self._parse_classes(class_view_pathname)
        relationship_views = await self._parse_class_relationships(class_view_pathname)
        packages_pathname = output_dir / "packages.dot"
        class_views, relationship_views, package_root = RepoParser._repair_namespaces(
            class_views=class_views, relationship_views=relationship_views, path=path
        )
        class_view_pathname.unlink(missing_ok=True)
        packages_pathname.unlink(missing_ok=True)
        return class_views, relationship_views, package_root

    @staticmethod

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Point generate_class_views at a directory containing __init__.py (a real Python package)
  2. Or create an empty __init__.py in the target directory
  3. Check path.exists() and (path/'__init__.py').exists() before calling, and skip silently if you want best-effort diagrams

Example fix

// before
await parser.generate_class_views(Path("scripts/"))  # no __init__.py -> ValueError

// after
target = Path("mypackage/")
assert (target / "__init__.py").exists()
await parser.generate_class_views(target)
Defensive patterns

Strategy: validation

Validate before calling

from pathlib import Path
p = Path(path)
if not (p / "__init__.py").exists():
    raise ValueError(f"{p} is not a package; generate_class_views needs __init__.py")

Type guard

from pathlib import Path

def is_python_package(path) -> bool:
    p = Path(path)
    return p.is_dir() and (p / "__init__.py").exists()

Try / catch

try:
    await parser.generate_class_views(path)
except ValueError as e:
    if "No module named __init__" in str(e):
        (Path(path) / "__init__.py").touch()  # or skip
        await parser.generate_class_views(path)
    else:
        raise

Prevention

When it happens

Trigger: Calling await parser.generate_class_views(path) where path has no __init__.py — e.g. a scripts folder, a data directory, or a namespace-package layout.

Common situations: Running class-view generation on non-package directories; pointing the parser at a flat script collection; refactoring that removed __init__.py files.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/0146343b7e580e92. Report an issue: GitHub.