如何在 Pydantic 中声明静态方法/类方法返回相关类的实例?

Joh*_*ard 1 python python-3.x flake8 python-typing pydantic

我正在使用 Python 3.7 并有类似的东西

class A(object):

  def __init__(self, value: int):
    self.value = value
  
  @classmethod
  def factory(cls, value: int) -> A:
    return A(value=value)
Run Code Online (Sandbox Code Playgroud)

是的,这是一个人为的示例,但我本质上是试图注释工厂函数以声明它返回 的实例,但是,当我尝试 在文件上A运行 linter 时,此操作会失败,因为它抱怨未定义。flake8A

有没有什么方法可以注释这个函数,这样 linter 就不会抱怨?

a_g*_*est 5

您可以通过注释来避免这种情况'A'

class A:
    @classmethod
    def factory(cls, value: int) -> 'A':
        ...
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用注释__future__

from __future__ import annotations
Run Code Online (Sandbox Code Playgroud)

并继续注释A