I have two TypeDict defined as follows:
class TypeFilter1(TypedDict): c: str d: floatclass TypeFilter2(TypedDict): e: float f: int
that I would like to use as types to construct two classes
class MyClass1(): def __init__(self, **kwargs:Unpack[TypeFilter1]) -> None: self.filters = [f"{key}:{values}" for key, values in kwargs.items() if key in TypeFilter1.__annotations__ ] self.params = ''.join(self.filters)class MyClass2(): def __init__(self, **kwargs:Unpack[TypeFilter2]) -> None: self.filters = [f"{key}:{values}" for key, values in kwargs.items() if key in TypeFilter2.__annotations__ ] self.params = ''.join(self.filters)
The role of the constructors is to parse **kwargs
to format a str
containing only those kwargs.items()
there are members of their respective TypeFilterX.__annotations__
:
A use case could be:
a = MyClass1(c="hello", d=2.0) # self.params -> "c:hello d:2.0b = MyClass2(e=2.1, g=3) # self.params -> "e:2.1"
Since both classes do the same thing, I thought that they could inherit the constructor from a BaseClass
but I wouldn't know how to implement BaseClass
so that it could parse **kwargs
using different TypeFilters
.
I tried to
- create a
GenericTypeFilter
as a parent of bothTyperFilterX
and sign thesuper().__init__(**kwargs)
asself, **kwargs:Unpack[GenericTypeFilter]
, but both classes return an emptystr
- define
**kwargs:Unpack[T]
insuper().__init__(**kwargs)
whereT = TypeVar("T", TypeFilter1,TypeFilter2)
, but `'TypeVar' object has no attribute - use
Any
. Same problem as above.
How should I do it? Moreover: now I have 2TypeFilterX
, but how would you handle the situation if I have N of them?
Thank you!