I really like the proposed syntax! Not only does it read better, but it
also makes it impossible to create a TypeVar with nonsensical combinations
of features, e.g. bound= with value restrictions. Do you think we could go
one step further and free users from the need to declare type vars?
As with the +T/-T proposal, my concern is that unless we put together a
deprecation timeline for the existing syntax, we would end up in a
situation where users have to learn both variants and tooling developers
have to do redundant work to support them.
On Sun, Oct 24, 2021 at 2:33 AM Jelle Zijlstra
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
(Examples taken from https://mypy.readthedocs.io/en/stable/generics.html)
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
(*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. _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: sergei.a.lebedev@gmail.com