问题
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 Expected type 'List[A]' (matched generic type 'List[_T]'), got 'List[B]' instead
on b
.
How do I get correct warnings, as obviously the types are fine.
回答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 likeList[Employee]
must exactly match the type annotation -- no subclasses or superclasses of the type parameter (in this exampleEmployee
) 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 import Sequence
a: Sequence[A] = []
b: Sequence[B] = []
c: Sequence[Base] = [*a, *b]
回答2:
In PyCharm you can type "# noinspection PyTypeChecker" above the line where you get warning.
来源:https://stackoverflow.com/questions/64481378/expected-type-lista-matched-generic-type-list-t-got-listb-instead