python / python/mypy

Wrong type inferred for a name conflicting with a module name in an import cycle

Offen
#7,419 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug priority-1-normal semantic-analyzer topic-import-cycles
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

The following is a failing test case which demonstrates the issue. In runtime, the type of a that is printed is str, however mypy reveals the type _importlib_modulespec.ModuleType.

[case testImportCycleWithOverriddenName]
# flags: --strict --no-incremental
import package

[file package/__init__.py]
a = 'a from __init__'
from .b import B

[file package/a.py]

[file package/b.py]
from . import a
class B: pass
print(type(a))
reveal_type(a)

[out]
package/b.py:4: note: Revealed type is 'builtins.str'

Note that if the two lines in __init__.py are swapped, the runtime type is indeed ModuleType.

I did not look at the code, but my uneducated guess is that the current "state" of __init__.py is not consulted when the from . import a in b.py is processed. This can probably be reduced further.

  • mypy 0.720
  • Python 3.7.4

Spawned from issue #7393.

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

Beginne mit dem bereitgestellten Fall testImportCycleWithOverriddenName und führe ihn mit --strict --no-incremental aus. Vergleiche package/init.py, package/a.py und package/b.py, insbesondere die Importreihenfolge und die Anweisung from . import a. Erledigt ist es, wenn reveal_type(a) builtins.str meldet und gleichzeitig das Ergebnis ModuleType erhalten bleibt, wenn die beiden Zeilen in init.py vertauscht werden.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers, devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

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