Skip to content

Conversation

@codenamenam
Copy link

@codenamenam codenamenam commented Sep 2, 2025

(Explain how this PR changes mypy.)

Fixes #19660

Allow instantiation of NoneType in type checker

This change fixes the error "Cannot instantiate type 'Type[None]'"
when calling NoneType() or type(None)().

By treating NoneType as a callable that returns None, mypy can now correctly
handle such calls without raising spurious errors.

Also, I added test case testTypeUsingTypeCNoneType covering:

  • direct calls to type(None)() and NoneType()
  • functions accepting type[None] and type[NoneType] parameters and invoking them

This ensures proper handling of NoneType instantiation and prevents spurious errors.

@github-actions

This comment has been minimized.

@sterliakov
Copy link
Collaborator

Note that this does not fix #19308 (but fortunately the magic comment only affects the first issue, so that's just a plain reference):

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:
    reveal_type(x)  # N: Revealed type is "type[builtins.str] | type[None]"

@codenamenam
Copy link
Author

codenamenam commented Sep 4, 2025

Thanks for the feedback, @sterliakov! It seems this PR doesn't fix #19308.
I've updated the PR description to only reference #19660.

Copy link
Contributor

@wyattscarpenter wyattscarpenter left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice!

Along with what's currently there, which ensures NoneType is callable, you should probably assert in your test case that the value produced by NoneType() and friends is None — um, or that its type is type[None], rather (or NoneType). Maybe you can use assert_type for this. Or possibly reveal_type plus expected notices, or some trick about narrowing, if assert_type doesn't work out for some reason.

@codenamenam
Copy link
Author

@wyattscarpenter Thanks for the review! I've modified the test case to use assert_type to verify the return type, as you suggested.

@github-actions
Copy link
Contributor

github-actions bot commented Sep 9, 2025

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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]"

3 participants