Python避免在相互引用中重新定义类时mypy失败

1 投票
1 回答
41 浏览
提问于 2025-04-12 17:10

考虑有一对类,它们在Python中表示同样的东西,并且每个类都有一个方法可以把一个转换成另一个。举个例子,就是把笛卡尔坐标转换成极坐标,反之亦然。

@dataclass
class CartesianCoordinates:
  x: float
  y: float
  
  def toPolarCoordinates(self) -> PolarCoordinates:
      radius = ...
      theta = ...
      result = PolarCoordinates(radius, theta)
      return result
  

@dataclass
class PolarCoordinates:
  radius: float
  theta: float

  def toCartesianCoordinates(self) -> CartesianCoordinates:
    x = ...
    y = ...
    result = CartesianCoordinates(x,y)
    return result

因为我在定义PolarCoordinates之前就使用了它,所以我尝试通过在CartesianCoordinates定义之前插入以下几行代码来提前声明它:

class PolarCoordinates:
    # forwarding declaration
    pass

这样做是有效的,代码可以正常运行,但像mypy这样的检查工具会因为类的重新定义而报错,错误信息是Name PolarCoordinates already defined

我知道在Python中真正的提前声明是不可能的,但有没有什么类似的办法,可以在类完全定义之前引用它,并且让像mypy这样的检查工具通过呢?

1 个回答

1

Python支持提前声明类型。你可以使用字符串来实现:

    def toPolarCoordinates(self) -> 'PolarCoordinates':

或者你可以使用一种叫“从未来导入”的方式(不需要德洛林汽车哦):

from __future__ import annotations

…

    def toPolarCoordinates(self) -> PolarCoordinates:

撰写回答