【发布时间】:2021-12-15 04:05:02
【问题描述】:
我想为我的自定义执行器类提供类型提示。在 Python 3.9 和 3.10 上,Mypy 希望将 Future[T] 作为泛型类型:
from concurrent.futures import Executor, Future
from typing import Any, Callable, TypeVar
T = TypeVar("T")
class MyExecutor(Executor):
def submit(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> Future[T]:
future = Future[T]()
# ...
但是,此代码在运行脚本时与 Python
Traceback (most recent call last):
File "example.py", line 6, in <module>
class MyExecutor(Executor):
File "example.py", line 7, in MyExecutor
def submit(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> Future[T]:
TypeError: 'type' object is not subscriptable
如何以向后兼容的方式为这种方法编写好的类型提示? typing-extensions 似乎不包含 Future 类型。
(我可以忍受无法在 Python
【问题讨论】:
-
我确实尝试了条件类型别名:Python >=3.9 上的
FutureOfT = Future[T]和旧版本上的FutureOfT = Future。但是使用它作为返回类型,我从 Mypy 得到error: Missing type parameters for generic type "FutureOfT" [type-arg]。