Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

isinstance(x, NoneType) doesn't get checked if the type annotation is None #13154

Closed
strny0 opened this issue Jul 16, 2022 · 4 comments
Closed
Labels
feature topic-type-narrowing Conditional type narrowing / binder

Comments

@strny0
Copy link
Contributor

strny0 commented Jul 16, 2022

Bug Report

isinstance check of mypy doesn't detect instances of NoneType (actual None), doesn't visit/check branches checked of isinstance() conditions.

Expected Behavior

from types import NoneType

def f(x: str | None):
    if isinstance(x, NoneType):
        reveal_type(x) # N: Revealed type is "None"
    elif isinstance(x, str):
        reveal_type(x) # N: Revealed type is "builtins.str"
    reveal_type(x) # N: Revealed type is "Union[builtins.str, None]"

Actual Behavior

from types import NoneType

def f(x: str | None):
    if isinstance(x, NoneType):
        reveal_type(x)
    elif isinstance(x, str):
        reveal_type(x) # N: Revealed type is "builtins.str"
    reveal_type(x) # N: Revealed type is "Union[builtins.str, None]"

Your Environment

@strny0 strny0 added the bug mypy got something wrong label Jul 16, 2022
@erictraut
Copy link

erictraut commented Jul 16, 2022

This is a pretty atypical way to check for None. The more idiomatic (and easier-to-read) approach takes advantage of the fact that None is a singleton and cannot be subclassed.

def f(x: str | None):
    if x is None:
        ...

@AlexWaygood AlexWaygood added feature topic-reachability Detecting unreachable code topic-type-narrowing Conditional type narrowing / binder and removed bug mypy got something wrong topic-reachability Detecting unreachable code labels Jul 16, 2022
@KotlinIsland
Copy link
Contributor

KotlinIsland commented Jul 17, 2022

@tyralla
Copy link
Collaborator

tyralla commented Apr 4, 2024

@strny0 We implemented this in Mypy 1.9, but I wasn't aware of this issue. I think it can be closed.

@JelleZijlstra
Copy link
Member

Confirmed mypy's behavior is now the expected behavior in the OP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

No branches or pull requests

6 participants