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

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

Post by Anonymous »

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.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post