python / python/mypy

Support type-narrowing on non-zero length sequences

Open
#14,244 0 comments 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

Feature

In the following example, mypy currently flags the final return statement because it thinks l could be empty, in which case the body of the for-loop would never execute, and therefore d could still be None. However, the preceding if-statement proves that the body of the for-loop will execute at least once, after which d must be int; it would be pretty cool if mypy could detect this and narrow d to int from that point forward.

def fun(d: int | None, l: list[int]) -> int:
    if len(l) == 0:
        return 0

    for x in l:
        d = (d or 0) + x

    # error: Incompatible return value type (got "Optional[int]", expected "int")
    # but actually we could safely narrow d to int
    return d

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

Reproduce the issue with the provided fun example and mypy, then trace the type-narrowing and control-flow analysis used for the non-empty list check and loop. No repository file or test is named; done means mypy safely accepts the final return and coverage verifies this narrowing without regressing related cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.