Skip to content

Surprising error involving bytes duck-type compatibility #12643

@dvarrazzo

Description

@dvarrazzo

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 = true

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable codetopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions