python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.13k stars 2.76k forks source link

Type narrowing in while loop #14807

Open tekumara opened 1 year ago

tekumara commented 1 year ago

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.

ankm20 commented 1 year ago

Would this be a good issue to explore for a beginner? If so, can this issue be assigned to me?