Python类相互引用时如何避免mypy因类重定义报错?
解决Python类互相引用导致mypy报错的方案
当两个类需要互相实现转换逻辑(比如笛卡尔坐标与极坐标类),直接提前引用未定义的类会触发mypy的类重定义报错,这里有两种实用的解决方法:
方法1:使用字符串形式的类型注解
Python 3.7+和mypy都支持将类型注解写成字符串格式,解释器会延迟解析类名,避免提前引用的问题:
from dataclasses import dataclass import math @dataclass class CartesianCoordinates: x: float y: float def toPolarCoordinates(self) -> 'PolarCoordinates': radius = (self.x**2 + self.y**2)**0.5 theta = math.atan2(self.y, self.x) return PolarCoordinates(radius, theta) @dataclass class PolarCoordinates: radius: float theta: float def toCartesianCoordinates(self) -> 'CartesianCoordinates': x = self.radius * math.cos(self.theta) y = self.radius * math.sin(self.theta) return CartesianCoordinates(x, y)
方法2:导入__future__ annotations(推荐)
Python 3.7+提供了from __future__ import annotations语法,导入后所有类型注解会自动被当作字符串处理,无需手动加引号,代码更简洁:
from __future__ import annotations from dataclasses import dataclass import math @dataclass class CartesianCoordinates: x: float y: float def toPolarCoordinates(self) -> PolarCoordinates: radius = (self.x**2 + self.y**2)**0.5 theta = math.atan2(self.y, self.x) return PolarCoordinates(radius, theta) @dataclass class PolarCoordinates: radius: float theta: float def toCartesianCoordinates(self) -> CartesianCoordinates: x = self.radius * math.cos(self.theta) y = self.radius * math.sin(self.theta) return CartesianCoordinates(x, y)
这两种方法既能保证代码正常运行,又能通过mypy的类型检查,完全替代会引发报错的空类前置声明方案。
内容的提问来源于stack exchange,提问作者roschach
相关产品推荐
相关产品推荐

