带有通用键和Callable [T]值的Python字典 [英] Python Dictionary with generic keys and Callable[T] values

查看:82
本文介绍了带有通用键和Callable [T]值的Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些命名元组:

JOIN = NamedTuple("JOIN", [])
EXIT = NamedTuple("EXIT", [])

我还具有处理每种类型的元组的功能:

I also have functions to handle each type of tuple with:

def handleJoin(t: JOIN) -> bool:
    pass

def handleExit(t: EXIT) -> bool:
    pass

我想做的是创建一个字典 handleTuple ,这样我可以这样称呼它:

What I want to do is create a dictionary handleTuple so I can call it like so:

t: Union[JOIN, EXIT] = #an instance of JOIN or EXIT
result: bool
result = handleTuple[type(t)](t)

我不知道如何定义所述字典.我试图定义一个通用的 T :

What I cannot figure out is how to define said dictionary. I tried defining a generic T:

T = TypeVar("T", JOIN, EXIT)
handleTuple: Dict[T, Callable[[T], bool]

但是我收到一条错误消息,提示类型变量T是未绑定的".我不明白.到目前为止,我最接近的是:

However I get an error saying "Type variable T is unbound" which I do not understand. The closest I have got so far is:

handleTuple: Dict[Type[Union[JOIN, EXIT]], bool]
handleTuple = {
    JOIN: True
    EXIT: False
}

以我想要的方式调用它效果很好,但是我无法弄清楚定义中的 Callable 部分,因此可以包含我的函数.我该怎么办

This works fine for calling it the way I want, however I cannot figure out the Callable part in the definition so I can include my functions. How can I do this

推荐答案

TypeVars仅在别名,类和函数中有意义.可以为查询定义 Protocol /a>:

TypeVars are only meaningful in aliases, classes and functions. One can define a Protocol for the lookup:

T = TypeVar("T", JOIN, EXIT, contravariant=True)

class Handler(Protocol[T]):
    def __getitem__(self, item: T) -> Callable[[T], bool]:
        ...

handleTuple: Handler = {JOIN: handleJoin, EXIT: handleExit}

特殊方法 self .__ getitem __(item)对应于 self [item] .因此,该协议定义了使用 item:T 访问 handleTuple [item] 会得出一些 Callable [[T],bool] .类型检查器(例如MyPy)了解 dict 是该协议的有效实现.

The special method self.__getitem__(item) corresponds to self[item]. Thus, the protocol defines that accessing handleTuple[item] with item: T evaluates to some Callable[[T], bool]. Type checkers such as MyPy understand that the dict is a valid implementation of this protocol.

由于该代码有效地实现了一次调度,因此定义了 <代码> functools.singledispatch 函数提供了开箱即用的行为:

Since the code effectively implements a single dispatch, defining a functools.singledispatch function provides the behaviour out of the box:

@singledispatch
def handle(t) -> bool:
    raise NotImplementedError

@handle.register
def handleJoin(t: JOIN) -> bool:
    pass

@handle.register
def handleExit(t: EXIT) -> bool:
    pass

t: Union[JOIN, EXIT]
result: bool
result = handle(t)

这篇关于带有通用键和Callable [T]值的Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆