[英]How can I type hint a dictionary where the key is a specific tuple and the value is known?
如何鍵入提示字典,其中鍵是特定元組且值已知?
例如,我想像這樣輸入提示:
class A:
pass
class B:
pass
class_map: = {
(str,): A
(int,): B
}
some_cls = class_map[(str,)]
用例將從一組已知的基數到 go 到先前使用這些基數定義的 class。
一個人可以做到這一點
__getitem__
簽名與 dict 使用的簽名不同__getitem__
,它從輸入字典中獲取值__getitem__
的重載我們可以做的另一件事是要求生成字典的輸入是一組凍結的元組。 然后可以鍵入提示允許的內容:
tuple_items: frozenset[
typing.Union[
typing.Tuple[typing_extensions.Literal['1invalid'], int],
typing.Tuple[typing_extensions.LiteralString, float]
]
] = frozenset({
('1invalid', 1),
('a', 1.234)
})
這啟用了類似於 TypedDict 的功能,但具有元組鍵。
import typing
class A:
pass
class B:
pass
class ClassMap:
def __init__(self, data: dict):
self.__data = data
@typing.overload
def __getitem__(self, name: typing.Tuple[typing.Type[str]]) -> typing.Type[A]: ...
@typing.overload
def __getitem__(self, name: typing.Tuple[typing.Type[int]]) -> typing.Type[B]: ...
def __getitem__(self, name):
return self.__data[name]
class_map = ClassMap({
(str,): A
(int,): B
})
some_cls = class_map[(str,)] # sees A, works!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.