Union interacts poorly with `isinstance`-based unreachability
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
This is probably already a bug report but the only place I know where this was mentioned was https://github.com/python/mypy/pull/13607#issuecomment-1236357236.
Including | None in a type makes isinstance type narrowing incorrectly report unreachability. This isn't only a problem with | None.
To Reproduce
class SymbolTableNode: pass
class FuncBase: pass
def bad(node: SymbolTableNode | None) -> None:
assert isinstance(node, FuncBase)
reveal_type(node) # unreachable
def good(node: SymbolTableNode) -> None:
assert isinstance(node, FuncBase)
reveal_type(node) # <subclass of SymbolTableNode and FuncBase>
Expected Behavior
No unreachable statements.
Actual Behavior
Unreachable reveal_type(node).
Your Environment
Reproduced in mypy-play.
- Mypy version used: 1.18.2
- Mypy command-line flags:
--warn-unreachable - Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.12
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 with the supplied reproducer in mypy-play using mypy 1.18.2 and --warn-unreachable, comparing the Union | None case with the non-Union case. Trace the isinstance-based narrowing behavior; done means reveal_type(node) is not reported as unreachable in the Union example while the expected narrowing remains intact.
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
- Clearly specified
- Newbie friendliness
- 45/100