I have implemented a factory pattern but Pyre-check trips over the type-hinting, thinking I want to instantiate the mapping dict type hint: type[MyClassABC]
Here is a minimum example, also a pyre-check playground that runs the checks online.
The goal is a factory pattern with proper type hinting. To achieve this I created an ABC for the class, with an abstract method for the __init__
, this way in my IDE I can see which parameters to supply thanks to the ABC init. However, I get the error:
33:15: Invalid class instantiation [45]: Cannot instantiate abstract class `MyClassABC` with abstract method `__init__`.
Because Pyre-check thinks I am going to instantiate the type-hint, type[MyClassABC]. How can I fix my type hinting so that it's still proper type hinting but Pyre-check doesn't think I'm instantiating an abstract method? I would like to keep the abstractmethod init for the parameter type hinting.
from abc import abstractmethod
class MyClassABC:
@abstractmethod
def __init__(self, name: str) -> None:
pass
class MyClass2(MyClassABC):
def __init__(self, name: str) -> None:
self.name = name
class MyClass(MyClassABC):
def __init__(self, name: str) -> None:
self.name = name
class ClassFactory:
MAPPING: dict[str, type[MyClassABC]] = {
"myclass": MyClass,
"myclass2": MyClass2,
}
@staticmethod
def get_class() -> type[MyClassABC]:
return ClassFactory.MAPPING["myclass"]
if __name__ == "__main__":
factory_cls = ClassFactory.get_class()
instance = factory_cls(name="test")