在旧版本的 Python 上使用现代输入功能

Jav*_*Dev 5 python python-typing pyright

因此,我正在使用 Python 编写一个事件发射器类。

目前代码如下所示:

from typing import Callable, Generic, ParamSpec

P = ParamSpec('P')

class Event(Generic[P]):
  def __init__(self):
    ...

  def addHandler(self, action : Callable[P, None]):
    ...

  def removeHandler(self, action : Callable[P, None]): 
    ...

  def fire(self, *args : P.args, **kwargs : P.kwargs):
    ...
Run Code Online (Sandbox Code Playgroud)

如您所见,注释依赖于,它仅在 python 3.10 中ParamSpec添加。typing

虽然它在 Python 3.10(在我的机器上)中运行良好,但在 Python 3.9 及更早版本(在其他机器上)中却失败了,因为这ParamSpec是一项新功能。

那么,如何ParamSpec在运行程序时避免导入或使用一些后备替代方案,同时不混淆编辑器中的输入(pyright)?

STe*_*kov 9

我不知道是否有任何理由重新发明轮子,但typing_extensions模块是由 python 核心团队维护的,支持python3.7和后来的,并且正是用于此目的。您可以只检查 python 版本并选择正确的导入源:

import sys

if sys.version_info < (3, 10):
    from typing_extensions import ParamSpec
else:
    from typing import ParamSpec
Run Code Online (Sandbox Code Playgroud)