How to properly type hint usage of child classes in list?

47 Views Asked by At

How do I properly type hint this:

from typing import Optional

class A: ...
class B(A): ...
class C(A): ...

my_dict: dict[str, list[Optional[A]]] = {"b": [], "c": []}

b: list[Optional[B]] = [B()]
c: list[Optional[C]] = [C()]
my_dict["b"] = b
my_dict["c"] = c

I obatain the following error in mypy:

error: Incompatible types in assignment (expression has type "list[B | None]", target has type "list[A | None]")  [assignment]

This works but is not what I want:

b: list[Optional[A]] = [B()]
c: list[Optional[A]] = [C()]`

Naively I assumed that the information would be inherited that B and C are children of A and thus the assignment is valid since this works:

bb: A = B()
cc: A = C()

Am I approaching it the wrong way? Can anyone help out?

I don't want it too verbose. Assume I have longer class names for B and C in real life.

1

There are 1 best solutions below

1
SIGHUP On

Not sure why you're using Optional here.

All three classes are instances of A so it's just:

class A: ...

class B(A): ...

class C(A): ...

my_dict: dict[str, list[A]] = {"b": [], "c": []}

my_dict["b"] = [B()]
my_dict["c"] = [C()]