python / python/mypy

Inconsistent narrowing for `builtins.type` and `typing.Type`

Open
#16,349 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-pep-585 topic-type-narrowing
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.