如何解决如何为子类实例的列表添加类型注释,例如以串联两个列表?
我想遍历List[A]
和List[Subclass of A]
并进行相同的循环。我可以看到的最好方法是将两个列表连接起来。但是,mypy对此并不满意。
如何将两者连接起来并使mypy开心?
当前,我做# type: ignore[operator]
。我想避免这种情况。
MVCE
# Core Library modules
from typing import Iterable
# Third party modules
from pydantic import BaseModel
class Animal(BaseModel):
height: float
weight: float
class Cat(Animal):
lives: int = 7
cats = [Cat(height=1,weight=2,lives=7),Cat(height=3,lives=1)]
animals = [Animal(height=9,weight=9)]
combined: Iterable[Animal] = cats + animals
for animal in combined:
print(animal)
给予
$ mypy untitled.py
untitled.py:20: error: Unsupported operand types for + ("List[Cat]" and "List[Animal]")
Found 1 error in 1 file (checked 1 source file)
解决方法
发生这种情况是因为list
是invariant(提供了一个示例)。
我可以提供两种解决方案:
- 将两个列表明确定义为
List[Animal]
才能成功进行串联:
cats: List[Animal] = [Cat(height=1,weight=2,lives=7),Cat(height=3,lives=1)]
animals: List[Animal] = [Animal(height=9,weight=9)]
combined: Iterable[Animal] = cats + animals
for animal in combined:
print(animal)
- 使用itertools.chain进行连续迭代:
cats = [Cat(height=1,lives=1)]
animals = [Animal(height=9,weight=9)]
for animal in itertools.chain(cats,animals):
print(animal)
,
如果不打扰您,请将List
更改为Sequence
from typing import Sequence
class Base: pass
class Derived(Base): pass
ds: Sequence[Derived] = [Derived()]
bs: Sequence[Base] = ds
您将获得的
$ mypy temp.py
Success: no issues found in 1 source file
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。