Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aatle opened this issue Oct 17, 2024 · 1 comment · May be fixed by python/mypy#17979
Open

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

aatle opened this issue Oct 17, 2024 · 1 comment · May be fixed by python/mypy#17979

Comments

@aatle
Copy link

aatle commented Oct 17, 2024

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
hauntsaninja added a commit to hauntsaninja/mypy that referenced this issue Oct 17, 2024
@hauntsaninja
Copy link
Collaborator

Took a look, seems pretty easy python/mypy#17979

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants