Skip to content Skip to sidebar Skip to footer

Expected Type 'list[a]' (matched Generic Type 'list[_t]'), Got 'list[b]' Instead On Correctly Typed Lists

from typing import List class Base(object): pass class A(Base): pass class B(Base): pass a: List[A] = [] b: List[B] = [] c: List[Base] = a + b I am getting Exp

Solution 1:

These types are not fine. List is invariant, meaning that a List[X] is not a substitute for List[Y] unless X and Y are exactly equal. Similarly, A <: Base does not imply List[A] <: List[Base] and likewise for B.

PEP 484: Covariance and contravriance

[...] By default generic types are considered invariant in all type variables, which means that values for variables annotated with types like List[Employee] must exactly match the type annotation -- no subclasses or superclasses of the type parameter (in this example Employee) are allowed.


A mutable container such as List is invariant because elements can be both inserted into (contravariant) and taken from (covariant) the list. If mutability is not required, using an immutable Sequence provides valid type annotation:

from typing importSequence

a: Sequence[A] = []
b: Sequence[B] = []
c: Sequence[Base] = [*a, *b]

Post a Comment for "Expected Type 'list[a]' (matched Generic Type 'list[_t]'), Got 'list[b]' Instead On Correctly Typed Lists"