Skip to content

Inconsistent narrowing for builtins.type and typing.Type #16349

Open
@tyralla

Description

@tyralla

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-585PEP 585 (builtin generics)topic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions