You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现类似typing.Callable且严格匹配types.FunctionType的类型注解?

需求:严格限制为FunctionType的类型注解

我需要一种类似typing.Callable[[args, ..], ret]的类型注解,但对输入的限制更严格。Callable仅要求实例具备合法的__call__()接口,而我需要的类型提示必须要求对象是具备合法__call__()接口的types.FunctionType。遗憾的是,目前并没有typing.FunctionType这类类型。

已尝试的方案

方案1:继承FunctionType并结合Generic

from typing import TypeVar, Generic
from types import FunctionType


_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")


class AnnotatedFunctionType(FunctionType, Generic[_T1, _T2]):
    def __call__(self, *args: _T1) -> _T2:
        pass

执行失败,报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type

方案2:Union组合Callable与FunctionType

from typing import Union, Callable
from types import FunctionType

AnnotatedFunctionType = Union[Callable, FunctionType]

范围过于宽泛,无法使用AnnotatedFunctionType[[arg1, arg2, ...], ret]的形式。

方案3:结合ParamSpec的Union方案

from typing import Union, Callable, TypeVar, ParamSpec
from types import FunctionType

_T = TypeVar("_T")
_P = ParamSpec("_P")
AnnotatedFunctionType = Union[Callable[_P, _T], FunctionType]

该方案可运行但不够严格,会允许任意函数或符合指定结构的可调用对象,且在mypy扫描时无法处理多参数。

我的思路

我猜测实现需求需要编写包含所需全部函数属性的Protocol类,尽管它会允许非FunctionType的类型,但能满足部分需求。若类型系统支持交集类型,或许可以使用Intersection[FunctionTypeProtocol[_T1, _T2], FunctionType]或FunctionTypeProtocol[_T1, T2] & FunctionType这类形式。

提问

哪种方法可以实现我的需求(且支持mypy等静态类型分析工具)?允许使用外部包。

内容的提问来源于stack exchange,提问作者oBrstisf8o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:28:15