Wie kann man einen Hinweis auf eine Zuordnung (DICT) mit wörtlichen Schlüssel eingeben?Python

Python-Programme
Anonymous
 Wie kann man einen Hinweis auf eine Zuordnung (DICT) mit wörtlichen Schlüssel eingeben?

Post by Anonymous »

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

Code: Select all

Literal[1, 2]
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?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post