首页 > 解决方案 > 如何为子类实例列表制作类型注释,例如连接两个列表?

问题描述

我想迭代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, weight=2, 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)

标签: pythontype-hintingmypy

解决方案


出现这种情况是因为list它是不变的(提供说明性示例)。

我可以提供两种解决方案:

  1. 明确定义两个列表以List[Animal]实现成功连接:
cats: List[Animal] = [Cat(height=1, weight=2, lives=7), Cat(height=3, weight=2, lives=1)]
animals: List[Animal] = [Animal(height=9, weight=9)]
combined: Iterable[Animal] = cats + animals

for animal in combined:
    print(animal)
  1. 使用itertools.chain进行连续迭代:
cats = [Cat(height=1, weight=2, lives=7), Cat(height=3, weight=2, lives=1)]
animals = [Animal(height=9, weight=9)]

for animal in itertools.chain(cats, animals):
    print(animal)

推荐阅读