python / python/mypy

Not None narrowing doesn't always work for nested field with list comprehensions

Open
#13,719 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

  1. 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
  1. 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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Use the provided dataclass and list-comprehension example as the first reproduction, then trace how mypy narrows attributes when multiple conditions are present. Add a regression test for this case and confirm that mypy accepts the return of the filtered list element without errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.