Can't narrow `Sequence[<X>]` to `Tuple[<X>, ...]` using `isinstance(..., tuple)`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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.net[^1]] (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, ....]'"
[^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
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.
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
Reproduce the example in the linked mypy-play.net case and inspect how mypy narrows isinstance(value, tuple) for Sequence[str]. Compare the result with the assert_type expectation and the linked pyright behavior; done means the narrowed value retains str elements as Tuple[str, ...].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100