Skip to content

Fix false positive "Cannot instantiate type[None]" error - #21018

Open
xovishnukosuri wants to merge 1 commit into
python:masterfrom
xovishnukosuri:fix-type-none-instantiation
Open

xovishnukosuri wants to merge 1 commit into
python:masterfrom
xovishnukosuri:fix-type-none-instantiation

Conversation

@xovishnukosuri

Copy link
Copy Markdown

Fixes #19660

What was wrong

NoneType() and type(None)() are valid Python -- both return None at runtime. Mypy was incorrectly reporting:

error: Cannot instantiate type "type[None]"  [misc]

for any call through a type[None] value.

Root cause

analyze_type_type_callee() in checkexpr.py handles type[X] calls by dispatching on the proper type of X. It covers Instance, UnionType, TypeVarType, TupleType, and TypedDictType, but had no case for NoneType. So calls through type[None] fell through to the unsupported-type error.

Fix

Add a NoneType case that returns a no-argument CallableType with return type NoneType. This matches runtime behaviour: NoneType() takes no arguments and returns None.

Test

def f(n: type[None]) -> None:
    x = n()
    reveal_type(x)  # Revealed type is "None"
    n(1)  # error: Too many arguments

x = type(None)()
reveal_type(x)  # Revealed type is "None"

Two new test cases added to test-data/unit/check-classes.test. All existing tests pass.

Calling type[None] (e.g. NoneType() or n() where n: type[None]) is
valid Python - NoneType() returns None at runtime. Add a NoneType case
in analyze_type_type_callee() so mypy accepts these calls and infers
the correct return type of None.

Fixes python#19660
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot instantiate type "Type[None]"

1 participant