type-hinting - 关于 Python 3.9+ 中类型提示的问题
问题描述
我有一个将回调函数作为参数的方法。
我想为回调函数签名指定类型提示。
问题是回调函数的签名是:
def callback_function(event, token, *args)
在哪里
type(event) = EventClass
type(token) = str
type(args) = tuple # of str
我可以这样写:
callable[[...], returntype]
但我想加强类型检查以使其有用,至少可以确保event
并token
正确指定。
请给点建议好吗?
解决方案
如前所述,考虑为此使用协议。
对于您的具体情况,它将如下所示:
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): ...
推荐阅读
- vb.net - Windows 窗体:访问控件外观属性
- javascript - 在 Express 应用程序中发出请求的两种方式之间的区别
- julia - 在远程进程中更改/访问远程变量
- css - two border color example explained
- express - mongoose query return array instead of object
- python - Python:如果名称用逗号分隔并在单独的行上,如何从文件中读取名称?
- c++ - 如何在 SFML for C++ 中单独访问每个形状/对象
- codenameone - 区分服务器端错误和连接问题
- python-3.x - 在 PyCharm 社区版上从 BeautifulSoup 导入 bs4 不起作用
- javascript - 来自 V-TAB vuetify 上的 API 的数据,使用 axios get vue js