-
- Notifications
You must be signed in to change notification settings - Fork 3.1k
Closed
Labels
bugmypy got something wrongmypy got something wrongtopic-reachabilityDetecting unreachable codeDetecting unreachable codetopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder
Description
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:
from typing import Union Buffer = Union[bytes, bytearray, memoryview] def f(data: Buffer) -> str: if not isinstance(data, bytes): data = bytes(data) return data.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 = true show_error_codes = true strict = trueMetadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongtopic-reachabilityDetecting unreachable codeDetecting unreachable codetopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder