I was thinking about Joren Hammudoglu's proposed pep adding `+T`/`-T` syntax for TypeVar variance and had a crazy idea: what if we had syntactic support for other kinds of TypeVar customization too?
For bounds we could overload the <= operator:
from typing import TypeVar, SupportsAbs
T = TypeVar("T")
def largest_in_absolute_value(*xs: T <= SupportsAbs[float]) -> T:
return max(xs, key=abs)
And for value restrictions we could use `in`:
def concat(x: T in (str, bytes), y: T) -> T:
return x + y
The first use of the TypeVar in the function definition would have the bound or constraints, and other uses would then follow the constraint set in the first use. Using in or <= on the same TypeVar more than once in a function definition is an error.
The nice thing about this syntax is that it puts all the information about the function definition in one place. You no longer have to create a named (and usually awkwardly named) TypeVar for each possible bound.
The syntax is reminiscent of that used in languages like Scala and TypeScript, although in those you would write something like `def largest_in_absolute_value<T <= SupportsAbs[float]>(*xs: T) -> T:`, which would require new syntax in Python.
I'm curious if other people think this would be a useful enhancement to the language.
_______________________________________________