python / python/mypy

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

Offen
#20,314 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-variables
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

*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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führe zunächst die bereitgestellte Reproduktion mypy --strict test.py mit mypy 1.18.2 aus und vergleiche die alte und die neue TypeVar-Syntax. Verfolge das Type-Checking-Verhalten für eingeschränkte int/float-TypeVars; die Arbeit ist abgeschlossen, wenn die Implementierung die dokumentierte Semantik der Einschränkungen konsistent anwendet und die Regressionstestabdeckung das Ergebnis erfasst.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.