You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have had a very specific issue in my own time, where two (can be thought of as n) generic types relate to each other and need to be grouped together. My use case was the return type of a function from one generic type should be another generic type, but only one specific concrete type of that generic type. I'm not sure if that makes sense, but the example below shows the rough implementation and syntax i am imagining for this. Frankly i have no idea if this is realistic or not, but i thought some others may have had some kind of issue similar to this.
fromtypingimportGroupedTypeVar, Generic# Define valid groups of typesTKey, TValue=GroupedTypeVar(
"TKey, TValue"
(str, int), # If the key is str, the value must be int
(bytes, float) # If the key is bytes, the value must be float
)
# Create a generic class using the grouped typesclassKeyValueStore(Generic[TKey, TValue]):
def__init__(self):
self.store: dict[TKey, TValue] = {}
defadd(self, key: TKey, value: TValue) ->None:
self.store[key] =valuedefget(self, key: TKey) ->TValue:
returnself.store[key]
The text was updated successfully, but these errors were encountered:
There is no sort of enforcing of types between generics though, even with overloads i dont think, if you could show me a way that would be great.
A better examples is:
classType1: ...
classType2: ...
classUsesType1:
defmethod(self) ->Type1: ...
classUsesType2:
defmethod(self) ->Type2: ...
TUses, TType=GroupedTypeVar(
"TUses, TType"
(UsesType1, Type1),
(UsesType2, Type2)
)
# Create a generic class using the grouped typesclassSomeClass(Generic[TUses, TType]):
def__init__(self, uses: TUses) ->None:
self.uses=usesdefadd(self) ->TType:
returnself.uses.method()
Im aware and i apologise that my example has gotten more abstract, but i hope im conveying my problem well enough.
I have had a very specific issue in my own time, where two (can be thought of as n) generic types relate to each other and need to be grouped together. My use case was the return type of a function from one generic type should be another generic type, but only one specific concrete type of that generic type. I'm not sure if that makes sense, but the example below shows the rough implementation and syntax i am imagining for this. Frankly i have no idea if this is realistic or not, but i thought some others may have had some kind of issue similar to this.
The text was updated successfully, but these errors were encountered: