Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13981

Signature Inheritance for **kwarg in constructor in python

$
0
0

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 both TyperFilterX and sign the super().__init__(**kwargs) as self, **kwargs:Unpack[GenericTypeFilter], but both classes return an empty str
  • define **kwargs:Unpack[T] in super().__init__(**kwargs) where T = 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!


Viewing all articles
Browse latest Browse all 13981

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>