Mypy seems to fail to narrow down union with not conditions. I couldn't find an issue already open on the topic.
To Reproduce
Running mypy on the following sample, an error is reported:
fromtypingimportUnionBuffer=Union[bytes, bytearray, memoryview]
deff(data: Buffer) ->str:
ifnotisinstance(data, bytes):
data=bytes(data)
returndata.decode()
$ mypy testunion.py testunion.py:9: error: Item "memoryview" of "Union[bytes, bytearray, memoryview]" has no attribute "decode" [union-attr]
This is unexpected because, after the if, the type of data is definitely bytes.
If a test if isinstance(data, (bytearray, memoryview)) is used instead there is no error. However this has likely a lower performance and requires more maintenance should other types be added to the union.
Your Environment
- Mypy version used: 0.941
- Python version used: 3.8.10
- In
pyproject.toml:
[tool.mypy]warn_unused_ignores = trueshow_error_codes = truestrict = true
Mypy seems to fail to narrow down union with
notconditions. I couldn't find an issue already open on the topic.To Reproduce
Running mypy on the following sample, an error is reported:
This is unexpected because, after the
if, the type ofdatais definitelybytes.If a test
if isinstance(data, (bytearray, memoryview))is used instead there is no error. However this has likely a lower performance and requires more maintenance should other types be added to the union.Your Environment
pyproject.toml: