【问题标题】:Question about type hinting in Python 3.9+关于 Python 3.9+ 中类型提示的问题
【发布时间】:2021-12-06 07:14:43
【问题描述】:

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

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

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

def callback_function(event, token, *args)

在哪里

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

我可以这样写:

callable[[...], returntype]

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

请给点建议?

【问题讨论】:

标签: type-hinting python-3.9


【解决方案1】:

考虑使用协议解决这个问题,如answered before。

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

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): ...

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2020-06-16
    • 1970-01-01
    • 2011-03-02
    • 2021-02-01
    • 2021-08-14
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多