PEP 696: Type defaults for TypeVarLikes

TLDR; This typing PEP proposes a way to specify a type parameter if omitted.

As far as I’m aware the only issue with the PEP from anyone in the typing community is about the way defaults for ParamSpecs should be represented (Question about the representation of ParamSpec Generic classes · Issue #1274 · python/typing · GitHub).
Some previous discussion on typing-sig (Mailman 3 Defaults for TypeVar-likes - Typing-sig - python.org).

Some places this could be useful in the standard library:

  • collections.abc.Generator - most people don’t use the last 2 type parameters, omitting them should be equivalent to collections.abc.Generator[T, None, None] or Any (I trust the opinions of the typeshed maintainers about this more than my own opinion here).
  • builtins.slice - Make slice generic over the start, stop and step parameters. start parameter should default to int , stop default to the type of start and step default to int | None .
  • datetime.datetime - for informing people of timezone awareness/naiveness at type time. default and bound should be timezone | None. datetime[timezone] would mean timezone-aware datetimes are expected to be passed, datetime[None] means naive datetimes and datetime[timezone | None] means you don’t care about awareness. This is relatively commonplace in other languages’ datetime libraries.
  • builtins.frozenset - default and potentially bound could be changed to Hashable to give better types and potentially catch more bugs before they reach production respectively.

Happy to answer any questions about this.

6 Likes

Are type checkers expected to always show the full type (e.g., Generator[str, None, None]) in error messages and other ouputs, even if the type arguments are default values? If this feature is widely used, this could lead to quite verbose error messages. (I imagine that library authors will be more inclined to make something generic if they can set a default value.) Maybe type checkers could at least omit default None type arguments in their output.

I think this is fine to leave up to each type checker, I personally wouldn’t because I think the parameters could be useful especially if the error is related to the omitted parameters.

This is an important point. I hope that libraries will be able to use this feature to produce shorter messages rather than longer: Generator[int] in the first example.

Yeah, maybe let them decide or perhaps they’ll provide an option. I find long messages inscrutable.

The issue is kind of similar to type aliases, right? Some code makes frequent use of type aliases, some of which can be quite long. When typecheckers report errors or notes using the expanded aliases the output can get very verbose and even hard to understand.

This is currently left up to typecheckers, and I don’t know if any of them simplify output using aliases.

1 Like