I have a base class that defines a class factory.
Then I have user defined classes which can extend the base class but which should use the class factory to create the class instance.
From a code perspective this works well and without issues, however I would like that the class factory is properly type hinted.
Unfortunately I can’t seem to make it work.
from typing import ParamSpec, TypeVar, Type
P = ParamSpec("P")
T = TypeVar("T")
class A:
def __init__(self, p1: int):
pass
@classmethod
def class_factory(cls: Type[T], *args: P.args, **kwargs: P.kwargs) -> T:
return cls(*args, **kwargs)
class B(A):
def __init__(self, p1: int, p2: str):
super().__init__(p1)
B.class_factory() # should be an error but is ok
B.class_factory('asdf', 1) # should be an error but is ok
If I a make a stand alone function this works well:
def create_class(f: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
return f(*args, **kwargs)
create_class(B, 'a', 'b') # <-- correctly identified as error
I tried annotating the class factory like the stand alone function but it doesn’t work.
Can anyone give me any hints?
Thank you for your help!