Skip to content

typing.TypeVar doesn't distinguish between (bound=None) and not providing a bound argument #129543

@bzoracler

Description

@bzoracler

Bug report

Bug description:

I was trying to reconstruct typing interfaces in a .pyi stub file by using runtime symbols. When trying to extract the value of the bound= argument to typing.TypeVar, I came across this result (which to be fair is documented in the signature):

>>> from typing import TypeVar
>>>
>>> T = TypeVar("T")
>>> print(T.__bound__ is None)
True

In static type checkers, an omitted bound= is equivalent to bound=builtins.object. The inconsistency with the runtime default value is problematic, because explicitly specifying bound=None also has a well-defined meaning to static type checkers (even if such a specification is rare):

(mypy Playground, pyright Playground)

from typing import TypeVar

T = TypeVar("T", bound=None)

def f(val: T, /) -> T:
    return val

f(None)  # OK
f(1)  # type-checker error

Not sure what the best course of action is here as any change to this will have backwards-compatibility concerns, but I think it's clear that static typing will not change an omitted bound= argument's interpretation to bound=None, as that would break most existing typed code.

CPython versions tested on:

3.9, 3.14

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-typingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions