typing icon indicating copy to clipboard operation
typing copied to clipboard

No way to have individual type variable substitutions in uniform tuples of parametrized types

Open KubaO opened this issue 4 years ago • 2 comments

Suppose we have:

T = TypeVar('T')
Element = tuple[T]

def fn(elements: tuple[Element, ...]): ...

The problem is that T is forced to be the same for every element, i.e. tuple[tuple[int], tuple[int]] will match, while tuple[tuple[float], tuple[int]] won't. Is there currently any support for this? If not, this would be a worthwhile feature - this would be a big help to get type checking and annotations in ctypes :)

KubaO avatar May 26 '21 23:05 KubaO

Why are you using a typevar here? It sounds like you want a Union instead. Also, note that tuple[T] means a tuple of exactly one element.

JelleZijlstra avatar May 26 '21 23:05 JelleZijlstra

Suppose now Element type may be one of [Type[c_int32], Union[c_int32, int]], [Type[c_void_p], Union[c_void_p, Type[None]]], etc. Lots of possible types - too many to list. But they'd generally follow some sort of a pattern that could be parametrized using type variables, as long as each type variable could be constrained to apply only within a subexpression, rather than entire type expression.

When dealing with something like tuple[tuple[Type[T], T], ...], it should be possible to select whether T is same everywhere, or reinstantiated for every element of the outer tuple.

KubaO avatar May 27 '21 02:05 KubaO