Not None narrowing doesn't always work for nested field with list comprehensions
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
When a list comprehension is used to filter class instances with some property not None and another condition, mypy doesn't later infer that instances from that list has a not None value for the property.
To Reproduce
- Write this code:
@dataclass
class HasOptionalField:
is_default: bool
field: str | None
def first_not_none_field(models: list[HasOptionalField]) -> str:
models_without_none = [model for model in models if model.is_default and model.field is not None]
return models_without_none[0].field
- Run mypy on above code with below settings
Expected Behavior
Mypy should pass without errors
Actual Behavior
Mypy has error: Incompatible return value type (got "Optional[str]", expected "str") [return-value]
When removing the model.is_default condition and keeping just model.field is not None then mypy doesn't emit errors.
Your Environment
- Mypy version used: 0.971
- Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files):
follow_imports = "normal"
ignore_errors = false
implicit_reexport = false
warn_redundant_casts = true
warn_unused_ignores = true
disallow_any_generics = true
disallow_untyped_defs = true
check_untyped_defs = true
allow_redefinition = false
local_partial_types = true
strict_optional = true
strict_equality = true
warn_unused_configs = true
warn_unreachable = true
warn_no_return = true
no_implicit_optional = true
strict = true
- Python version used: 3.10.4
- Operating system and version: Windows 11
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Usa l’esempio fornito di dataclass e list-comprehension come prima riproduzione, quindi traccia come mypy restringe gli attributi quando sono presenti più condizioni. Aggiungi un regression test per questo caso e conferma che mypy accetti la restituzione dell’elemento filtrato della lista senza errori.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 45/100