【问题标题】:Generic `Future` type compatibility with Python <3.9通用的 `Future` 类型与 Python <3.9 的兼容性
【发布时间】: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]。

标签: python typing


【解决方案1】:

到目前为止,我能找到的最佳解决方法是:

import sys
from concurrent.futures import Executor, Future
from typing import Any, Callable, Generic, TypeVar, cast

T = TypeVar("T")

if sys.version_info < (3, 9):
    class FutureType(Generic[T]):
        def set_exception(self, exc_info: BaseException) -> None:
            ...
        def set_result(self, result: Any) -> None:
            ...
else:
    FutureType = Future

class MyExecutor(Executor):
    def submit(
        self, fn: Callable[..., T], *args: Any, **kwargs: Any
    ) -> FutureType[T]:
        future = cast(FutureType[T], Future())
        # ...

此版本的脚本可在 Python

我确实希望有一种更清洁的方式仍然与 Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2022-06-14
    • 2012-06-30
    • 1970-01-01
    相关资源
    最近更新 更多