python / python/mypy

A 'type only' module import should not count as importing a module

Offen
#11,503 3 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

given:

my-app/
├─ package/
│  ├─ __init__.py
│  ├─ things.py
├─ entry.py
├─ mod.py

entry.py:

import mod
import package

mod.func(package.things.Thing())

mod.py:

def func(it):
    ...

In typeshed/bundled stubs: mod.pyi

from package.things import Thing

def func(it: Thing) -> None: ...
OR, if this is fake imported in the .py module: mod.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING
    # do a type import so doesn't cause circular imports or slow down loading
    from package.things import Thing

def func(it: Thing) -> None:
    ...

package.things.py

class Thing:
    ...

When mypy --strict entry.py is executed, no error is generated.
When python entry.py is run: AttributeError: module 'package' has no attribute 'things'

Mypy treats the 'type import' as importing package.things, when in reality it isn't. I understand this is consistent with what TYPE_CHECKING should do, but seems really sus if you ask me.

This more seriously affects typeshed, where all imports are fake and mypy will think all fakely imported modules are really imported.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere das Verhalten mit entry.py, mod.py, package/init.py und package/things.py unter Verwendung der bereitgestellten mypy --strict- und Python-Befehle. Beginne damit nachzuverfolgen, wie der Type-only-Import in mod.pyi oder der TYPE_CHECKING-Block behandelt wird, und füge dann einen Regressionstest hinzu, der zeigt, dass package.things zur Laufzeit nicht verfügbar gemacht werden darf.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.