dict literals inferred like immutable Mapping
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
dict literal behaves as though it is inferred to be (immutable) Mapping
To Reproduce
class OrmBase:
pass
class Orm1(OrmBase):
pass
class Orm1Prime(OrmBase):
pass
class Orm2(OrmBase):
pass
class Orm2Prime(OrmBase):
pass
def func(orm: Union[Orm1, Orm2]):
orm_mapper = {
Orm1: Orm1Prime,
Orm2: Orm2Prime,
}
mapped: Union[Type[Orm1Prime], Type[Orm2Prime]] = orm_mapper[orm.__class__]
# Incompatible types in assignment (expression has type "Type[OrmBase]",
# variable has type "Union[Type[Orm1Prime], Type[Orm2Prime]]") [E]
return mapped
Expected Behavior
dict is a MutableMapping, which is invariant with respect to value types. The Union on mapped should be acceptable here. (Pyright has no issue with this.)
Actual Behavior
The Union is rejected, apparently because the parent class is expected (see the error message above).
Adding a plain dict annotation resolves the error:
orm_mapper: dict = { ...
I believe this resolves the error by telling Mypy that this is a MutableMapping with invariant VT and not a Mapping with covariant VT_co. typing's definitions of both
Your Environment
- Mypy version used: 0.910
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files):
[mypy]
plugins = sqlalchemy.ext.mypy.plugin
ignore_missing_imports = True
[mypy-sqlalchemy.*]
- Python version used: 3.9.6
- Operating system and version: Fedora 34 (Workstation)
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der Ausführung der bereitgestellten Reproduktion mit mypy 0.910 und vergleiche den inferierten Typ des nicht annotierten dict-Literals mit der explizit annotierten Version. Verfolge den Inferenzpfad für dict-Literals und überprüfe, dass die Zuweisung die erwartete Union akzeptiert, ohne die Typsicherheit zu schwächen; das Issue ist gelöst, wenn die Reproduktion erfolgreich ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- tooling
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 38/100