python-3.x 我怎样才能键入hint一个字典,其中键是一个特定的元组,并且值是已知的?

wkyowqbh  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(94)

我怎样才能键入hint一个字典,其中键是一个特定的元组,并且值是已知的?
例如,我想像这样输入hint一个dict:

class A:
    pass

class B:
    pass

class_map: = {
    (str,): A
    (int,): B
}

some_cls = class_map[(str,)]

用例将从一组已知的基转换到以前使用这些基定义的类。

kuarbcqp

kuarbcqp1#

一个人可以通过

  • 创建一个新的类ClassMap,允许查找字典键
  • 注意:dict不能被子类化,因为我们的__getitem__签名与dict使用的签名不同
  • 在ClassMap中定义__getitem__,它从输入字典中获取值
  • 在ClassMap中定义一个__getitem__的重载,并使用元组输入和类型提示输出
  • 创建ClassMap的示例
  • 使用它和类型提示工作
  • 通过我的检查

这启用了类似于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!

相关问题