class B:
pass
class InheritsB1(B):
pass
class InheritsB2(B):
pass
class A:
prop: list[B]
class InheritsA1(A):
prop: list[InheritsB1]
class InheritsA2(A):
prop: list[InheritsB2]
With this code mypy raises Incompatible types in assignment (expression has type "List[InheritsB2]", base class "A" defined the type as "List[B]")
.
How can I make this work?
InheritsB1
is a subclass of B
, so list[InheritsB1]
is always a list of B
. How can I tell mypy that it's not incompatible? Or, how can I tell mypy that the prop
in A
is "list of B
or any specific subclass of B
"?
I understand the issue here: mypy trouble with inheritance of objects in lists. But in this case I want the prop
object to be a list of a specific instances (B
or any subclass of B
). I know it will never be mixed, as in it will always be list[B]
or list[SubclassOfB1]
or list[SubclassOfB2]
, never list[SubclassOfB1 | SubclassOfB2]
. How can I do this?