python / python/mypy

Spurious error for code that fails truthy-bool even when not enabled

Aperta
#18,026 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

It seems that code failing to pass the truthy-bool check can have spurious errors that occur, even when that optional error code isn't enabled.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=53000744586f03d23bb53f807d5a0ea0

class Truthy: 
    pass
    # def __bool__(self) -> bool: return True

def foo(truthies: list[Truthy]) -> None:
    sum(1 if x else 0 for x in truthies)

Expected Behavior

This code should typecheck fine: sum on ints is sensible!

Uncommenting the __bool__ definition (so that the truthy-bool error no longer applies, if it was enabled) passes type checking.

Actual Behavior

main.py:4: error: Generator has incompatible item type "int"; expected "bool"  [misc]

(Note that the truthy-bool error doesn't occur, as expected, because it isn't enabled.)

When running with that enabled one sees:

$ mypy testing.py --enable-error-code=truthy-bool
testing.py:7: error: Generator has incompatible item type "int"; expected "bool"  [misc]
testing.py:7: error: "x" has type "Truthy" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]

Your Environment

  • Mypy version used: 1.12.1
  • Mypy command-line flags: N/A see playground
  • Mypy configuration options from mypy.ini (and other config files): N/A see playground
  • Python version used: 3.12

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il riproduttore mypy-play collegato ed esegui l’esempio con e senza --enable-error-code=truthy-bool. Traccia l’errore item-type segnalato per l’espressione generatrice e verifica che il codice superi il controllo dei tipi senza il codice di errore opzionale, preservando al contempo la diagnosi truthy-bool prevista quando è abilitato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.