Skip to content

isinstance on runtime-checkable protocols does not correctly narrow unions inferred by TypeGuard #13753

Open
@twoertwein

Description

@twoertwein

Bug Report

from __future__ import annotations

from collections.abc import Sized
from typing import (
    Iterator,
    Sequence,
)

from typing_extensions import TypeGuard


def is_list_like(x: object) -> TypeGuard[Iterator | Sequence]:  # not the best example but it demonstrates the issue
    ...


def is_nested_list(xs: object) -> bool:
    return (
        is_list_like(xs)
        and isinstance(xs, Sized)  # after this xs is assumed to be Sized but it should be Sized while simultaneously also being an Iterator or a Sequence
        and len(xs) > 0
        and all(is_list_like(x) for x in xs)  # "Sized" has no attribute "__iter__" (not iterable)  [attr-defined]
    )

Your Environment

  • Mypy version used: 0.981 (same for 0.971)
  • Python version used: 3.10.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / bindertopic-typeguardTypeGuard / PEP 647

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions