Expected type 'List[A]' (matched generic type 'List[_T]'), got 'List[B]' instead on correctly typed lists

隐身守侯 提交于 2021-01-03 07:07:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!