Skip to content

Surprising error involving bytes duck-type compatibility #12643

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:

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

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