python / python/mypy

Type narrowing fails on type(None) or NoneType

Open
#19,308 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Type narrowing can't remove type(None) from a union.

To Reproduce

def get_class(x: int) -> type[str | None]:
    if x > 0:
        return str
    else:
        return type(None)


x = get_class(1)
if x is type(None):
    print("hi")
else:
    x("test") # Cannot instantiate type "Type[None]"

Expected Behavior

Type narrowing should eliminate that possibility. It works with None, but not NoneType.

Actual Behavior

Cannot instantiate type "Type[None]"

Your Environment

mypy 1.16.0
Python 3.12.10

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 provided Python reproduction and run it against mypy 1.16.0, comparing the type(None) case with the working None case. Done means the reported narrowing no longer leaves x as Type[None] in the else branch while preserving the existing behavior for None.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.