python / python/mypy

mypy gets confused between non-re-exported import and a submodule of the same name

Open
#16,216 0 comments 3 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

This is happening in opencv, relevant issue: https://github.com/opencv/opencv-python/issues/901

Type stub cv2 imports typing
Module cv2.typing also exists
The following raises a mypy error, as expected

import cv2
_ = cv2.typing.MatLike  # Module "cv2" does not explicitly export attribute "typing" Mypy [attr-defined]

(note that this will work at runtime, by that's because cv2 doesn't actually import typing at runtime AND does dynamic imports to expose all its submodules, so mypy is correct here in terms of static type-checking)

The following works, and is accepted by mypy, as expected

import cv2.typing
_ = cv2.typing.MatLike

The issue comes from importing both:

import cv2
import cv2.typing

Note that pyright handles this case correctly.

(A clear and concise description of what the bug is.)

To Reproduce

Download the reproduction, then run mypy . at the root. See error
Run python test.py, see the symbol printed out.
Minimal repro.zip

Expected Behavior

No error in repro

Actual Behavior

PS C:\Users\Avasam\Desktop\Minimal repro> mypy .
test.py:4: error: Module has no attribute "Foo"  [attr-defined]
Found 1 error in 1 file (checked 3 source files)

Your Environment

  • Mypy version used: mypy 1.5.1 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.9.13

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

Extract the linked Minimal repro.zip and first run mypy . from its root, then run python test.py to confirm the runtime behavior. Trace how mypy handles import cv2, import cv2.typing, and the later cv2.typing.MatLike access. Done means the reproduction reports no error while preserving the expected runtime result.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.