I am making class that takes keyword arguments and stores them in the attribute. Also I want to add typing using Generic
and TypedDict
.
TV = TypeVar("TV")
class MyClass(Generic[TV]):
init_kwargs: TV
def __init__(self, **kwargs: Unpack[TV]) -> None:
self.init_kwargs = kwargs
It isn’t the full functional of this class, this code is given for example.
Usage example:
class MyTD(TypedDict, total=False):
arg1: int
arg2: str
a: MyClass[MyTD] = MyClass(arg1=4, arg2="foo")
b: MyClass[MyTD] = MyClass(arg1="bar", arg2=6) # Should be type error here
reveal_type(a.init_kwargs['arg1']) # Should be int
reveal_type(a.init_kwargs['arg2']) # Should be str
But type checker (mypy) throws error:
def __init__(self, **kwargs: Unpack[TV]) -> None:
# ^^
# Unpack item in ** argument must be a TypedDict
Is there a way to do this correctly and how to do it?