Unbounded TypeVar on variable's type info

Hello, I have a use case that I'm not sure if this is something the current typing system could handle (and if it should). Basically, I'd like to use generics on a variable's type info to constrain the variable a bit more. My prime example would be to constrain a dict value based on the dict key, something like that: U = TypeVar("U", bound=Item) _CHECKS_TO_APPLY: dict[Type[U], list[Type[Check[U]]]] In that example, _CHECKS_TO_APPLY stores what kind of "Check" is applicable on a type "Item". The "Check" type is a hierarchy of specialized generic classes taking the type "Item" they can check as a generic parameter. I put a longer example there: https://gist.github.com/Gaasmann/beeebf526c163280cff796b842ee800a Right now, I'm not sure if what I'm doing is valid. In any case, mypy isn't happy: generic_typing.py:61: error: Type variable "generic_typing.U" is unbound generic_typing.py:61: note: (Hint: Use "Generic[U]" or "Protocol[U]" base class to bind "U" inside a class) generic_typing.py:61: note: (Hint: Use "U" in function signature to bind "U" inside a function) Do you think this use case makes sense, and if this is something the system should be able to handle? Thanks, -- Nicolas

There's no good way to express what you want for a dictionary type as such. I suggest wrapping the `_CHECKS_TO_APPLY` dictionary as a class. To be strict when constructing the dictionary, you could have a wrapper class that only inserts key-value pairs that match each other: ``` class DependentDict: def __setitem__(self, key: Type[U], value: list[Type[Check[U]]]) -> None: ... def __getitem__(self, key: Type[U]) -> list[Type[Check[U]]]: ... ``` That way, only valid key-value pairs can be inserted or retrieved. Playground link: https://mypy-play.net/?mypy=latest&python=3.10&gist=1abab7b9712e3223eea1cd975c214ffb On Sun, May 22, 2022 at 10:49 AM Nicolas Haller <nicolas@haller.im> wrote:
-- S Pradeep Kumar

There's no good way to express what you want for a dictionary type as such. I suggest wrapping the `_CHECKS_TO_APPLY` dictionary as a class. To be strict when constructing the dictionary, you could have a wrapper class that only inserts key-value pairs that match each other: ``` class DependentDict: def __setitem__(self, key: Type[U], value: list[Type[Check[U]]]) -> None: ... def __getitem__(self, key: Type[U]) -> list[Type[Check[U]]]: ... ``` That way, only valid key-value pairs can be inserted or retrieved. Playground link: https://mypy-play.net/?mypy=latest&python=3.10&gist=1abab7b9712e3223eea1cd975c214ffb On Sun, May 22, 2022 at 10:49 AM Nicolas Haller <nicolas@haller.im> wrote:
-- S Pradeep Kumar
participants (2)
-
Nicolas Haller
-
S Pradeep Kumar