簡體   English   中英

如何鍵入提示字典,其中鍵是特定元組且值已知?

[英]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。

一個人可以做到這一點

  • 制作一個新的 class ClassMap,這將允許字典鍵查找
    • 注意:dict 不能被子類化,因為我們的__getitem__簽名與 dict 使用的簽名不同
  • 在 ClassMap 中定義__getitem__ ,它從輸入字典中獲取值
  • 在 ClassMap 中使用元組輸入和類型提示 output 定義__getitem__的重載
  • 創建 ClassMap 的實例
  • 使用它並輸入提示工作
  • 通過 mypy 檢查

我們可以做的另一件事是要求生成字典的輸入是一組凍結的元組。 然后可以鍵入提示允許的內容:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM