python / cpython

The Python programming language
https://www.python.org
Other
63.65k stars 30.49k forks source link

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

Closed otethal closed 4 days ago

otethal commented 4 days ago

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

Eclips4 commented 4 days ago

Related: https://github.com/python/cpython/issues/90802

brianschubert commented 4 days ago

I can confirm that this bisects to issue Eclips4 linked (commit 870b22b9c442d035190d2b8fb82256cd9a03da48)

JelleZijlstra commented 4 days ago

This is correct and intentional. "Types" in the Python type system are much broader than "instances of type", and we're intentionally loose in the runtime so that users can experiment with putting other objects in the type system.