Skip to content

TypeVar() does not check that the bound parameter is a type #127106

@otethal

Description

@otethal

Bug report

Bug description:

According to the documentation of TypeVar

The upper bound of a type variable can be a concrete type, abstract type (ABC or Protocol), or even a union of types

However, in python 3.12.7, it is possible to create a TypeVar instance with a non-type bound:

Python 3.12.7 (tags/v3.12.7:0b05ead877f, Nov 13 2024, 14:08:49) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import typing
>>> typing.TypeVar('T', bound=3).__bound__
3

In python 3.10.12, the same code leads to an exception:

Python 3.10.12 (main, Nov  6 2024, 20:22:13) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import typing
>>> typing.TypeVar('T', bound=3).__bound__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/typing.py", line 804, in __init__
    super().__init__(bound, covariant, contravariant)
  File "/usr/lib/python3.10/typing.py", line 731, in __init__
    self.__bound__ = _type_check(bound, "Bound must be a type.")
  File "/usr/lib/python3.10/typing.py", line 176, in _type_check
    raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Bound must be a type. Got 3.

CPython versions tested on:

3.10, 3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions