Skip to content Skip to sidebar Skip to footer

How Do I Make A Type Annotation For A List Of Subclass Instances, E.g To Concatenate Two Lists?

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.

Solution 1:

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

I can offer two solutions:

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

Solution 2:

If it doesn't bother you, change List to Sequence

from typing importSequenceclassBase: passclassDerived(Base): pass

ds: Sequence[Derived] = [Derived()]
bs: Sequence[Base] = ds

with which you'll get

$mypytemp.pySuccess:noissuesfoundin1sourcefile

Post a Comment for "How Do I Make A Type Annotation For A List Of Subclass Instances, E.g To Concatenate Two Lists?"