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:
- 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)
- 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)
Post a Comment for "How Do I Make A Type Annotation For A List Of Subclass Instances, E.g To Concatenate Two Lists?"