by Anonymous » 19 Aug 2025, 11:41
Ich möchte ein Wörterbuch (oder ein äquivalentes Objekt) eingeben, das von einer Reihe von buchstäblichen Auswahl an einige Ausgänge abgebaut wird. Ich verwende PyType als meinen Typ-Checker.
Code: Select all
from typing import Literal
SupportedKey = Literal["one", "two"]
d : dict[SupportedKey, int] = {"one": 1, "two": 2}
PyType erkennt jedoch nicht, dass "eins" und "zwei" tatsächlich unterstützt werden s und fällt daher mit
fehl
Code: Select all
Type annotation for d does not match type of assignment [annotation-type-mismatch]
Annotation: dict[Literal['one', 'two'], int]
Assignment: dict[str, Literal[1, 2]]
< /code>
Beachtenstr
ist nicht nicht buchstäblich ['eins', 'zwei']
[*] zugewiesen
ist int
Ich habe eine explizitere Methode ausprobiert, wobei die Schlüssel mit entsprechenden Tippen konstruiert sind:
Code: Select all
from typing import Literal, Final
SupportedKey = Literal["one", "two"]
KEY_ONE: Final[SupportedKey] = "one"
KEY_TWO: Final[SupportedKey] = "two"
d : dict[SupportedKey, int] = {KEY_ONE: 1, KEY_TWO: 2}
< /code>
Dies schlägt jedoch ähnlich - die Schlüssel werden immer noch als allgemeiner als wörtlicher als wörtlich abgeleitet: < /p>
Type annotation for d does not match type of assignment [annotation-type-mismatch]
Annotation: dict[Literal['one', 'two'], int]
Assignment: dict[str, int]
Was ist der beste Weg, um eine korrekt getippte Zuordnung mit Literalen als Schlüssel zu erreichen?
[url=viewtopic.php?t=14917]Ich möchte[/url] ein Wörterbuch (oder ein äquivalentes Objekt) eingeben, das von einer Reihe von buchstäblichen Auswahl an einige Ausgänge abgebaut wird. Ich verwende PyType als meinen Typ-Checker.[code]from typing import Literal
SupportedKey = Literal["one", "two"]
d : dict[SupportedKey, int] = {"one": 1, "two": 2}
[/code]
PyType erkennt jedoch nicht, dass "eins" und "zwei" tatsächlich unterstützt werden s und fällt daher mit
fehl[code]Type annotation for d does not match type of assignment [annotation-type-mismatch]
Annotation: dict[Literal['one', 'two'], int]
Assignment: dict[str, Literal[1, 2]]
< /code>
Beachtenstr[/code] [b] ist nicht [/b] nicht buchstäblich ['eins', 'zwei']
[*] zugewiesen[code]Literal[1, 2][/code] [b] ist [/b] int
Ich habe eine explizitere Methode ausprobiert, wobei die Schlüssel mit entsprechenden Tippen konstruiert sind:
[code]from typing import Literal, Final
SupportedKey = Literal["one", "two"]
KEY_ONE: Final[SupportedKey] = "one"
KEY_TWO: Final[SupportedKey] = "two"
d : dict[SupportedKey, int] = {KEY_ONE: 1, KEY_TWO: 2}
< /code>
Dies schlägt jedoch ähnlich - die Schlüssel werden immer noch als allgemeiner als wörtlicher als wörtlich abgeleitet: < /p>
Type annotation for d does not match type of assignment [annotation-type-mismatch]
Annotation: dict[Literal['one', 'two'], int]
Assignment: dict[str, int]
[/code]
Was ist der beste Weg, um eine korrekt getippte Zuordnung mit Literalen als Schlüssel zu erreichen?