python/pycharm type hinting with base class?

Viewed 679

the base class here is actually an abstract class provides basic methods with type hints, and the subclasses overwrite them with the same parameters.

i tried the below code, wanted to let values in dictionary mp hint these basic methods but it doesn't work.

from typing import Dict

class Base:
    pass

class A(Base):
    pass

class B(Base):
    pass


mp: Dict[str, Base] = {
    "A": A,
    "B": B
}

the Pycharm IDE warned Expected type 'Dict[str, Base]', got 'Dict[str, Union[A, B]]' instead.

i wonder what the correct way is

1 Answers

as the above friend @MaxNoe mentioned, i should use the code below

from typing import Dict, Type

class Base:
    pass

class A(Base):
    pass

class B(Base):
    pass


mp: Dict[str, Type[Base]] = {
    "A": A,
    "B": B
}
Related