Type narrowing in while loop
Open
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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