如何注释类方法返回该类的实例

Gar*_*rwe 6 python type-hinting python-typing

使用PEP 484,有没有办法注释 classmethod 返回该类的实例?

例如

@dataclass
class Bar:

    foo: str

    @classmethod
    def new_from_foo(cls, foo) -> Bar
        ...
Run Code Online (Sandbox Code Playgroud)

或者

    @classmethod
    def new_from_foo(cls, foo) -> cls
Run Code Online (Sandbox Code Playgroud)

Ara*_*Fey 7

诀窍是使用 aTypeVarcls参数连接到返回注释:

from typing import TypeVar, Type

T = TypeVar('T')

class Bar:
    @classmethod
    def new_from_foo(cls: Type[T], foo) -> T:
        ...
Run Code Online (Sandbox Code Playgroud)

  • 老实说,对我来说,这看起来像是 mypy 中的一个错误。据我所知,它只发生在类方法中——而且只发生在数据类中。编辑:找到相关的 [github 问题](https://github.com/python/mypy/issues/5263)。 (3认同)