Skip to content

Incorrect code generation for relative imports inside __init__.py #1070

Closed
python/mypy
#17979
@aatle

Description

@aatle

Inaccurate code is generated for a relative import statement inside an __init__.py module of a nested package (usually leading to an ImportError at program runtime).

Conditions:

  • Relative import statement
  • Module is the __init__.py module
  • The package / directory of the __init__.py is not the top-level one (file not the highest __init__.py)

Outcome:
The statement tries to import from the parent package of the correct package, generally causing an ImportError.
E.g. (typed) from .module import foo -> (compiled) from ..module import foo

To reproduce:
Have mypy 1.12.0, and its mypyc extension, installed.
Create a file structure as follows:

.
└── a/
    ├── __init__.py
    └── b/
        ├── __init__.py
        └── bar.py

In a/b/__init__.py, add a valid relative import statement:

from . import bar

Compile with mypyc a in the terminal, successfully.
Execute the following statement to run a/b/__init__.py, in the python IDLE or a new ./main.py file:

import a.b

Result:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "a\b\__init__.py", line 1, in <module>
    from . import bar
ImportError: cannot import name 'bar' from 'a' (~\mypyc-test\a\__init__.cp312-win_amd64.pyd)

The statement tries to import a.bar instead of the intended a.b.bar

Expected behavior
The compiled program runs with no errors, the relative import statement is generated correctly.

Actual behavior
The generated relative import is off by one level, often causing an import error when running the compiled program.

Environment

  • Mypy version used: 1.12.0 (compiled)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12.4
  • Windows 11

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions