python / python/mypy

Type narrowing in while loop

Open
#14,807 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

Feature

example.py

from __future__ import annotations
import typing as t

class Node:
    parent: Node | None = None

N = t.TypeVar("N", bound=Node)

def find_ancestor(node: Node, node_type: t.Type[N]) -> N | None:
    ancestor = node.parent
    while ancestor and not isinstance(ancestor, node_type):
        ancestor = ancestor.parent
    return ancestor

mypy 1.0.1 errors with:

example.py:13: error: Incompatible return value type (got "Optional[Node]", expected "Optional[N]")  [return-value]

Would be great to narrow the type to N here and avoid the spurious error.

Pitch

Type narrowing in a while loop would improve inference. pyright already does this.

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

Start by running mypy against the provided example.py and reproducing the return-value error. Then inspect the type-narrowing control flow for while loops and compare the behavior with pyright. Done means the loop narrows the value to N after isinstance and the example no longer reports the error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.