Skip to content

bool is available even if *constraints of TypeVar is the exact types int and float #20314

@hyperkai

Description

@hyperkai

*Memo:

  • mypy --strict test.py
  • mypy 1.18.2
  • Python 3.14.0
  • Windows 11

The doc says 'Must be exactly str or bytes' about *constraints to make difference between bound and *constraints as shown below:

*Memo:

  • From my understanding:
    • Setting bound, the type and the subtypes are available.
    • Setting *constraints, only the exact types are available but not the subtypes.

T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytes

But bool is available even if *constraints is the exact types int and float as shown below:

<With TypeVar (Old syntax)>:

from typing import TypeVar, Generic

T = TypeVar('T', int, float)

class MyCls(Generic[T]):
    num: T

    def __init__(self, x: T) -> None:
        self.num = x

           # ↓↓↓↓↓↓↓↓↓↓↓↓
mycls = MyCls[bool](True)
# No error

<Without TypeVar (New syntax)>:

class MyCls[T: (int, float)]:
    num: T

    def __init__(self, x: T) -> None:
        self.num = x

           # ↓↓↓↓↓↓↓↓↓↓↓↓
mycls = MyCls[bool](True)
# No error

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions