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

Can't narrow Sequence[<X>] to Tuple[<X>, ...] using isinstance(..., tuple) #16933

Open
finite-state-machine opened this issue Feb 20, 2024 · 0 comments · May be fixed by #17099
Open

Can't narrow Sequence[<X>] to Tuple[<X>, ...] using isinstance(..., tuple) #16933

finite-state-machine opened this issue Feb 20, 2024 · 0 comments · May be fixed by #17099
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder

Comments

@finite-state-machine
Copy link

finite-state-machine commented Feb 20, 2024

Bug Report

Using isinstance(<Sequence[X]>, tuple) narrows the type of <Sequence[X]> to Tuple[Any, ...], not Tuple[X, ...] as one would expect.

To Reproduce

[mypy-play.net]
[pyright-play.net1] (pyright handles this as expected)

from __future__ import annotations
from typing_extensions import (
        assert_type,
        Sequence,
        Tuple,
        )

value: Sequence[str]

if isinstance(value, tuple):
    assert_type(value, Tuple[str, ...])
            # expected: (this works)
            # actual: "Expression is of type 'tuple[Any, ...]',
            #          not 'tuple[str, ....]'"

Expected Behavior

if instance(value, ...) should only ever narrow the type of value

Actual Behavior

Mypy narrows the container type, but forgets the element type

Your Environment

  • Mypy version used: 1.8.0; bug exists back to at least 1.0
  • Mypy command-line flags: (none)
  • Mypy configuration options from mypy.ini (and other config files): (none)
  • Python version used: 3.8, 3.12

Existing issues

While it seems extremely unlikely that this issue hasn't been reported, I haven't been able to locate anything obviously related among the ~217 issues that mention both isinstance and tuple. Issue #2456 may be vaguely related.

Footnotes

  1. the pyright example code is slightly modified (1) to avoid an error around value being uninitialized, and (2) to reflect that pyright behaves as expected

@finite-state-machine finite-state-machine added the bug mypy got something wrong label Feb 20, 2024
@finite-state-machine finite-state-machine changed the title Can't narrow Sequence[<X>] to Tuple[x, ...] using isinstance(..., tuple) Can't narrow Sequence[<X>] to Tuple[<X>, ...] using isinstance(..., tuple) Feb 20, 2024
@AlexWaygood AlexWaygood added the topic-type-narrowing Conditional type narrowing / binder label Feb 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
2 participants