Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type narrowing in while loop #14807

Open
tekumara opened this issue Mar 1, 2023 · 1 comment
Open

Type narrowing in while loop #14807

tekumara opened this issue Mar 1, 2023 · 1 comment
Labels

Comments

@tekumara
Copy link

tekumara commented Mar 1, 2023

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
Copy link

ankm20 commented Mar 23, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants