python / python/mypy

Error in mypy when using any() or all() to check for None in a iterable

Aperta
#17,218 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

Mypy raises errors indicating the absence of attributes for objects of type "None" when using any() or all().

To Reproduce

from dataclasses import dataclass


def get_hobby_description(hobby: str) -> ...: ...


def get_best_friend_info(best_friend: str) -> ...: ...


@dataclass
class Person:
    name: str
    age: int
    hobby: str | None = None
    best_friend: str | None = None


person = Person(name="name", age=0, hobby=None, best_friend=None)
if not all((person.hobby, person.best_friend)):
    raise ValueError

if not any((person.hobby, person.best_friend)):
    raise ValueError

hobby_description = get_hobby_description(person.hobby)
best_friend_info = get_best_friend_info(person.best_friend)

Expected Behavior

The code should be recognized as correct since it checks for the absence of None among the variables person.hobby and person.best_friend.

Actual Behavior

Mypy raises errors indicating the absence of attributes for objects of type "None" when using any() or all().

error: Argument 1 to "get_hobby_description" has incompatible type "str | None"; expected "str"  [arg-type]
error: Argument 1 to "get_best_friend_info" has incompatible type "str | None"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Mypy command-line flags: No
  • Mypy configuration options from mypy.ini (and other config files): No
  • Python version used: 3.12.2

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

Non viene indicato alcun file sorgente né alcun test. Inizia eseguendo il riproduttore dataclass fornito con mypy 1.10.0 e verifica come any() e all() influenzano il narrowing degli attributi opzionali. Il lavoro è completato quando il comportamento segnalato è stato risolto oppure la sua semantica prevista è documentata e coperta da un test di regressione.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.