On Fri, Sep 4, 2020, at 12:31, Sebastian Rittau wrote:
This was previously discussed in https://github.com/python/typing/issues/307.
It would often be useful to be able to specify a default type for type vars. A few examples:
I, too, have wanted this multiple times, and agree with all the reasons laid out by Sebastian. One common case I can add is `Generator[Foo, None, None]`. I think it would make a lot of sense to default `SendType` and `ReturnType` to None. There is a workaround mentioned in the issue of using a type alias, e.g. SimpleGenerator = Generator[T, None, None] but this requires coming up with a name and complicating the API, which never pulls its weight. So I wonder if anyone has a good idea for a syntax? One suggestion is T = TypeVar("T", default=int) but I personally don't like it for two reasons: 1. I think the default is more of a property of the generic type than the TypeVar itself, which can be reused in multiple types. 2. I think it causes an ambiguity when a default is followed by non-defaults, e.g. given YieldType = TypeVar("YieldType") SendType = TypeVar("SendType, default=int) ReturnType = TypeVar("ReturnType") class Generator(Generic[YieldType, SendType, ReturnType]): ... how should `Generator[str, bytes]` be interpreted? Of course it would have been ideal if it were possible to use the exact same syntax and semantics (minus the types) of function arguments, even including positional-only and keyword-only type parameters, but I don't see how it works out syntactically. Maybe one of the newer PEPs help here? Ran