python / python/mypy

Relative imports in stub modules checking live code

Open
#12,102 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Hi all! I'm trying to get to the bottom of this issue with stub imports, and I can't even find information to tell me if this is actually expected behaviour. Please see repro.

To Reproduce

A quick setup running this series of shell commands follows:

>>> $ mkdir module
>>> $ mkdir module-stubs
>>> $ touch module/__init__.py
>>> $ touch module-stubs/submodule.pyi
>>> $ echo "from . import submodule" > module-stubs/__init__.pyi
>>> $ echo "import module" > run.py
>>> $ mypy run.py 
module-stubs/__init__.pyi:1: error: Module 'module' has no attribute 'submodule'
Found 1 error in 1 file (checked 1 source file)

Expected Behavior

I would have expected that an import within the stub module still would understand that the stub module exists, and use the stub submodule to verify the import.
The real module can be doing any number of dynamic things during the import to ensure "submodule" is available.

OR this is expected behaviour and I need to adjust my expectations.

Actual Behavior

The result appears to be that mypy goes looking in the actual python package for the module and not within the stub.
module-stubs/__init__.pyi:1: error: Module 'module' has no attribute 'submodule'

Actually creating the submodule in the python package removes this error.

Your Environment

Mypy versions tested on 0.931 and 0.812 with same results.
OS version: linux mint 20.3

Thanks a lot everyone.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the report using the shell commands in the issue, especially module-stubs/init.pyi, module-stubs/submodule.pyi, and run.py. Start by tracing how mypy resolves the relative import in the stub package; done when the behavior is documented or the import resolves consistently with the intended stub-module semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.