python / python/mypy

False-positive [attr-defined] when importing classes and functions from a file with the same name as the parent package

Open
#19,410 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

Suppose you have the following directory tree:

thebug/
thebug/run.py
thebug/__init__.py
thebug/thebug.py

Attempting to import anything from thebug.py (using from thebug import whatever) will cause mypy to complain error: Module "thebug" has no attribute "whatever" [attr-defined].

To Reproduce

  1. mkdir thebug
  2. cd thebug
  3. touch __init__.py
  4. vim thebug.py and type in the following contents:
class A:
    def __init__(self) -> None:
        self.val = "a"
  1. vim run.py and type in the following contents:
from thebug import A
var: A = A()
print(var.val)
  1. Run it to make sure it works:
$ python3 run.py
a
  1. Type-check it:
mypy run.py

Actual Behavior

$ mypy run.py
run.py:1: error: Module "thebug" has no attribute "A"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.16.1
  • Mypy command-line flags: none, as shown above
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12.3

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 shown thebug/init.py, thebug/thebug.py, and run.py files, then run mypy run.py. Trace how the import from thebug is resolved when the package and module share a name; done means the example type-checks without the false-positive while retaining the reported attribute checking.

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
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.