Incorrect type narrowing when swapping variables after isinstance check
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Swapping the variables doesn't seem to make mypy swap their types and the second variable is left with its type as before the swap.
Changing the example below to use a temp variable fixes the issue:
tmp = a
a, b = b, tmp
reveal_type(a) # note: Revealed type is "test.Sub1"
reveal_type(b) # note: Revealed type is "test.Sub2"
To Reproduce
class Base:
pass
class Sub1(Base):
pass
class Sub2(Base):
pass
def f(a: Base, b: Base) -> None:
if isinstance(b, Sub1) and isinstance(a, Sub2):
a, b = b, a
reveal_type(a) # note: Revealed type is "test.Sub1"
reveal_type(b) # note: Revealed type is "test.Sub1"
Expected Behavior
Type of b is Sub2 after the swap.
Actual Behavior
Type of b is Sub1 after the swap.
Your Environment
- Mypy version used: mypy 2.2.0+dev.52de0c739d2f066ea06fa9a886bc8fcc9fa079c6
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.13.5
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 the minimal Python reproduction with mypy and tracing type narrowing for tuple assignment after the isinstance checks. Add a regression test covering the swap, and verify that reveal_type(a) is Sub1 while reveal_type(b) is Sub2.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100