Description
(I apologize if this has already been reported; searching the repository's issues for "type(None)" returns 554 open issues and 1438 closed issues, so you'll have to forgive me if I didn't check every one.)
Bug Report
Consider the following code:
from typing import Optional
def func(x: Optional[int]) -> int:
if isinstance(x, type(None)):
return 0
else:
return x + 1 # This is line 7
If mypy (either v0.782 or commit 6b0f7d7) is run on this code with the default settings, it fails with:
mypy02.py:7: error: Unsupported operand types for + ("None" and "int")
mypy02.py:7: note: Left operand is of type "Optional[int]"
Found 1 error in 1 file (checked 1 source file)
However, if the line if isinstance(x, type(None)):
is replaced with if x is None:
, the code passes mypy.
I believe mypy's current behavior is in error, as the only difference from the if x is None:
version is that the type(None)
version also catches hypothetical subtypes of None
, which makes to difference to whether x
will be int
or not in the else:
branch. In both versions, x
in the else:
branch should only be int
, not Optional[int]
.
(Yes, I realize that writing isinstance(x, type(None))
is highly unusual, but this is simplified from more complex code that used an expression of the form isinstance(x, (int, type(None)))
and still failed to type-check unless I rewrote it to isinstance(x, int) or x is None
.)
Your Environment
- Mypy version used: both version 0.782 and commit 6b0f7d7
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini
(and other config files): none - Python version used: 3.8.5
- Operating system and version: macOS 10.13.6