Skip to content

isinstance(x, SomeClass) doesn't imply x is not None #2015

Answered by erictraut
dnaaun asked this question in Q&A
Discussion options

You must be logged in to vote

In the first code snippet, you have annotated arg1 with the type annotation Union[str, int]. That means it must either be a str or an int. It cannot be a None. Therefore the conditional statement if arg1 is None is nonsensical in this context, and pyright narrows the type of arg1 to Never within the if branch.

In the second code snippet, pyright will do the right thing if it knows the type of NoneExistent. However, it has no knowledge of this type because you've imported it from a "library_without_types". Without this type knowledge, it has no way of knowing whether it derives from str. It conservatively assume that it might, so the isinstance type narrowing logic doesn't narrow the type of

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@dnaaun
Comment options

@erictraut
Comment options

@dnaaun
Comment options

Answer selected by dnaaun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants