Warum ist dict [str, str] für die Zuordnung [STR | int, str] (Mapping -Schlüsseltyp ist nicht kovariante)?
Posted: 20 Aug 2025, 04:00
Angesichts dieses Code
Beide MyPy 1.16.0 und Pyright 1.1.400 berichten, dass es ungültig ist, dem Argument M d zuzuweisen. Zum Beispiel Pyright Ausgänge:
einem Mutablemapping [STR | int, str] wäre schlecht (die Callee könnte int Schlüssel in das dict einfügen), aber Mapping ist unveränderlich.
Code: Select all
from collections.abc import Mapping
def my_fn(m: Mapping[str | int, str]):
print(m)
d = {"a": "b"}
my_fn(d)
Code: Select all
error: Argument of type "dict[str, str]" cannot be assigned to parameter "m" of type "Mapping[str | int, str]" in function "my_fn"
"dict[str, str]" is not assignable to "Mapping[str | int, str]"
Type parameter "_KT@Mapping" is invariant, but "str" is not the same as "str | int" (reportArgumentType)
< /code>
Warum ist dies der Fall? Ich verstehe, warum das Zuweisen von DICT [STR, STR]