Inconsistent narrowing for `builtins.type` and `typing.Type`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
The following difference is due to Mypy handling typing.Type via TypeType, for which it does not try to create an intersection, and builtins.type as an Instance, for which it does:
# flags: --python-version 3.9 --warn-unreachable
from typing import Type
t1: Type
t2: type
class C: ...
if isinstance(t1, C):
reveal_type(t1) # E: Statement is unreachable
if isinstance(t2, C):
reveal_type(t2) # N: Revealed type is "__main__.<subclass of "type" and "C">"
I encountered this problem when working on #16330, which affects type checking a sphinx function.
Interestingly, things are consistent when annotating explicitly with Any:
# flags: --python-version 3.9 --warn-unreachable
from typing import Any, Type
t1: Type[Any]
t2: type[Any]
class C: ...
if isinstance(t1, C):
reveal_type(t1) # E: Statement is unreachable
if isinstance(t2, C):
reveal_type(t2) # E: Statement is unreachable
So, Mypy maybe misunderstands t2: type?
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 reproducer in the issue using the stated Python 3.9 and --warn-unreachable settings. Trace how Mypy narrows typing.Type through TypeType versus builtins.type through Instance, then compare the behavior with the explicit Any examples. Done means the inconsistent narrowing is resolved and the shown cases produce consistent diagnostics and revealed types.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100