[New-bugs-announce] [issue47068] Improve __repr__ of TypeVar

Kaleb Barrett report at bugs.python.org
Sat Mar 19 13:19:22 EDT 2022

New submission from Kaleb Barrett <dev.ktbarrett at gmail.com>:

Currently the __repr__ for TypeVar includes the variance information and the type name (for example ~T, +T_co, -T_contra), but it does not contain bound or constraint information. I'm not sure what value including variance but not bound information in the __repr__ is, both are important for the use of interfaces that use that variable.

I propose we add the bound and constraint information to the __repr__. The __repr__ is arbitrary as popular type checking tools, such as mypy, and documentation tools, such as Sphinx, do not use the standard __repr__. Nor is the __repr__ eval()-able like many builtin types. And for documentation tools that do use the standard __repr__, this improvement will be propagated to those tools. (I originally requested this improvement in pdoc which uses the standard __repr__; the maintainer agreed with this improvement.)

Bounds can be represented using an ASCII representation of the subset operator "<=" and then the bound. Constraints can be represented using "<=" with a tuple of the constraints. Perhaps spaces should be added around the "<=" operator? I have no opinion.

Some examples of the proposed __repr__:
>>> TypeVar("T")
>>> IntT = TypeVar("IntT", bound=int)
>>> IntT
>>> TypeVar("AnyStr", str, bytes)
~AnyStr<=(str, bytes)
>>> List[IntT]

messages: 415562
nosy: ktbarrett
priority: normal
severity: normal
status: open
title: Improve __repr__ of TypeVar
type: enhancement
versions: Python 3.11

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list