如何为子类实例列表制作类型注释,例如连接两个列表? [英] How do I make a type annotation for a list of subclass instances, e.g to concatenate two lists?

查看:28
本文介绍了如何为子类实例列表制作类型注释,例如连接两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历 List[A]List[Subclass of A] 并执行相同的循环.我能看到的最好的方法是连接两个列表.然而,mypy 对此并不满意.

I want to iterate over List[A] and List[Subclass of A] and do the same loop. The best way I can see to do that is to concatenate the two lists. However, mypy is not happy about it.

如何将两者连接起来并让 mypy 开心?

How can I concatenate the two and keep mypy happy?

目前,我做# type: ignore[operator].如果可能,我想避免这种情况.

Currently, I do # type: ignore[operator]. I would like to avoid that, if possible.

# 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)

推荐答案

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

This situation occurs because list is invariant (provides an illustrative example).

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

I can offer two solutions:

  1. 将两个列表显式定义为 List[Animal] 以成功连接:
  1. Explicitly define both lists as List[Animal] for successful concatenation:

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 进行连续迭代:
  1. Use itertools.chain for consecutive iteration:

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)

这篇关于如何为子类实例列表制作类型注释,例如连接两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆