Not None narrowing doesn't always work for nested field with list comprehensions
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Verwende das bereitgestellte dataclass- und list-comprehension-Beispiel als erste Reproduktion und verfolge anschließend, wie mypy Attribute eingrenzt, wenn mehrere Bedingungen vorhanden sind. Füge für diesen Fall einen regression test hinzu und bestätige, dass mypy die Rückgabe des gefilterten Listenelements ohne Fehler akzeptiert.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 45/100