[New-bugs-announce] [issue46769] Improve documentation for `typing.TypeVar`

Alex Waygood report at bugs.python.org
Wed Feb 16 12:01:18 EST 2022


New submission from Alex Waygood <Alex.Waygood at Gmail.com>:

There are three variants of `TypeVar`s:

(1) TypeVars that are neither constrained nor bound: `T = TypeVar("T")`
(2) TypeVars that are bound: `U = TypeVar("U", bound=str)`
(3) TypeVars that are constrained: `V = TypeVar("V", str, bytes)`

The third variant is important for annotating certain functions, such as those in the `re` module. However, it has a number of issues (see https://github.com/python/typing/discussions/1080 for further discussion):

(1) It has somewhat surprising semantics in many situations.
(2) It is difficult for type checkers to deal with, leading to a number of bugs in mypy, for example.
(3) Many users (especially people relatively inexperienced with Python typing) reach for constrained TypeVars in situations where using bound TypeVars or the @overload decorator would be more appropriate.

Both PEP 484 and the documentation for the typing module, however:

(1) Give examples for variants (1) and (3), but not for variant (2), which is treated as something of an afterthought.
(2) Do not mention that TypeVars can be bound to a union of types, which is an important point: `T = TypeVar("T", str, bytes)` has different semantics to `T = TypeVar("T", bound=str|bytes)`, and often the latter is more appropriate.

----------
assignee: docs at python
components: Documentation
messages: 413342
nosy: AlexWaygood, Jelle Zijlstra, docs at python, gvanrossum, kj, sobolevn
priority: normal
severity: normal
stage: needs patch
status: open
title: Improve documentation for `typing.TypeVar`
type: behavior
versions: Python 3.10, Python 3.11, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46769>
_______________________________________


More information about the New-bugs-announce mailing list