Skip to content

New GroupedTypeVar type #1899

@MatthewMckee4

Description

@MatthewMckee4

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.

from typing import GroupedTypeVar, Generic

# Define valid groups of types
TKey, 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 types
class KeyValueStore(Generic[TKey, TValue]):
    def __init__(self):
        self.store: dict[TKey, TValue] = {}

    def add(self, key: TKey, value: TValue) -> None:
        self.store[key] = value

    def get(self, key: TKey) -> TValue:
        return self.store[key]

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions