Warum ist dict [str, str] für die Zuordnung [STR | int, str] (Mapping -Schlüsseltyp ist nicht kovariante)?

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Warum ist dict [str, str] für die Zuordnung [STR | int, str] (Mapping -Schlüsseltyp ist nicht kovariante)?

by Anonymous » 20 Aug 2025, 04:00

Angesichts dieses Code

Code: Select all

from collections.abc import Mapping

def my_fn(m: Mapping[str | int, str]):
print(m)

d = {"a": "b"}
my_fn(d)
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:

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] 
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.

Top