如何正确标注返回 classmethod 的包装器?
结论
把 from_xcal_wrapper 的返回类型从普通 Callable 改成 classmethod 描述符类型,比如 classmethod[VProp, [VPropParser | ElementAdapter | Element], VProp]。同时,给被装饰方法的 cls 标上 type[Self],并在模块顶部加上 from __future__ import annotations。这样类型检查器就能把装饰后的属性识别为类方法。
原因
@classmethod 在运行时会把函数包装成描述符,但类型检查器不会根据函数体里的 @classmethod 去推断外层装饰器的返回值。原来的返回类型是 Callable[[type[VProp], ...], VProp],类型检查器会把它当作普通可调用对象;它出现在类里时,会按实例方法绑定第一个参数,于是拿 Self 和 type[VProp] 比较,报出 Cannot take first argument because it is Self. not type[Self]。
classmethod[...] 的泛型参数顺序是:类实例类型、去掉 cls 后的参数列表、返回类型。比如 classmethod[VProp, [VPropParser | ElementAdapter | Element], VProp] 表示:这个类方法属于 VProp 类型,调用时只需传 xml,返回 VProp。
解决步骤
- 导入
Self:Python 3.11+ 用from typing import Self,旧版本用from typing_extensions import Self。 - 在文件顶部加
from __future__ import annotations,避免运行时对classmethod[...]求值。 - 把
from_xcal_wrapper的返回类型改成classmethod[VProp, [VPropParser | ElementAdapter | Element], VProp]。 - 内部的
wrapper保留@classmethod,并标注cls: type[VProp]。 - 被装饰的
from_xcal的cls标成type[Self],返回类型写Self。
代码示例
from __future__ import annotations
from typing import Callable, TypeVar
from typing_extensions import Self
VProp = TypeVar("VProp")
def from_xcal_wrapper(
func: Callable[[type[VProp], VPropParser, Parameters], VProp],
) -> classmethod[VProp, [VPropParser | ElementAdapter | Element], VProp]:
@classmethod
def wrapper(
cls: type[VProp],
xml: VPropParser | ElementAdapter | Element,
) -> VProp:
# 在这里把 xml 转换成 func 需要的 VPropParser 和 Parameters
parser: VPropParser = ...
parameters: Parameters = ...
return func(cls, parser, parameters)
return wrapper
class X:
@from_xcal_wrapper
def from_xcal(
cls: type[Self],
parser: VPropParser,
parameters: Parameters,
) -> Self:
# ...
return cls(...)
如果类型检查器版本较旧,不支持 classmethod 的三参数泛型写法,可以先把返回类型写成字符串注解,或者升级 mypy/pyright。不同检查器对描述符泛型的支持程度可能不一样,关键是返回值必须标成 classmethod[...],不能只写 Callable[...]。
注意事项
- 不要用
if TYPE_CHECKING: from_xcal_wrapper = classmethod替换整个函数。这样会丢掉参数转换逻辑,运行时行为也会变。 wrapper内部的参数转换需要自己实现。上面的parser = ...只是占位,要按你的ElementAdapter、Element和Parameters的实际逻辑补全。- 如果 Ruff 仍提示
cls应改成self,先看 Ruff 有没有启用类型推断。这类提示通常是它没把装饰器结果识别成类方法;类型检查器通过后一般会缓解。 classmethod的泛型参数顺序别写反:第一个是类实例类型,第二个是参数列表,第三个是返回类型。
备注:内容仅供参考。
