首页 > 解决方案 > 关于 Python 3.9+ 中类型提示的问题

问题描述

我有一个将回调函数作为参数的方法。

我想为回调函数签名指定类型提示。

问题是回调函数的签名是:

def callback_function(event, token, *args)

在哪里

type(event) = EventClass
type(token) = str
type(args) = tuple  # of str

我可以这样写:

callable[[...], returntype]

但我想加强类型检查以使其有用,至少可以确保eventtoken正确指定。

请给点建议好吗?

标签: type-hintingpython-3.9

解决方案


如前所述,考虑为此使用协议。

对于您的具体情况,它将如下所示:

from typing import Protocol, TypeAlias

returntype: TypeAlias = int

class MyCallable(Protocol):
    def __call__(self, event: EventClass, token: str, *args: str) -> returntype: ...


def some_function(callback: MyCallable): ...

推荐阅读