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

Python 如何为子类实例列表创建类型注释,例如连接两个列表?,python,type-hinting,mypy,Python,Type Hinting,Mypy,我想迭代List[A]和List[A的子类]并执行相同的循环。我能看到的最好的方法是将两个列表连接起来。然而,mypy对此并不满意 我怎样才能将两者结合起来,让mypy开心呢 目前,我做#键入:忽略[operator]。如果可能的话,我想避免这种情况 MVCE #核心库模块 从输入导入可编辑 #第三方模块 从pydantic导入BaseModel 动物类别(基本模型): 高度:浮动 重量:浮子 类别猫(动物): 寿命:int=7 猫=[猫(身高=1,体重=2,寿命=7),猫(身高=3,体重=2,

我想迭代
List[A]
List[A的子类]
并执行相同的循环。我能看到的最好的方法是将两个列表连接起来。然而,mypy对此并不满意

我怎样才能将两者结合起来,让mypy开心呢

目前,我做
#键入:忽略[operator]
。如果可能的话,我想避免这种情况

MVCE
#核心库模块
从输入导入可编辑
#第三方模块
从pydantic导入BaseModel
动物类别(基本模型):
高度:浮动
重量:浮子
类别猫(动物):
寿命:int=7
猫=[猫(身高=1,体重=2,寿命=7),猫(身高=3,体重=2,寿命=1)]
动物=[动物(身高=9,体重=9)]
组合:Iterable[动物]=猫+动物
对于组合中的动物:
印刷品(动物)
给予


如果您不介意,请将
列表
更改为
序列

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

出现这种情况的原因是
list
is(提供了一个示例)

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

  • 将两个列表明确定义为
    List[Animal]
    ,以便成功连接:
  • 用于连续迭代:

  • 否,
    combined
    包含
    Animal
    的实例,但不包含class对象
    Animal
    ,谢谢您的更正。用键入更新了我的答案。这是否回答了您的问题?
    $ mypy temp.py
    Success: no issues found in 1 source file
    
    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)
    
    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)