如何为子类实例列表创建类型注释,例如连接两个列表?

How do I make a type annotation for a list of subclass instances, e.g to concatenate two lists?

我想遍历 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)

如果不介意,请将 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

出现这种情况是因为listinvariant(提供了一个说明性示例)。

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

  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)