Skip to content

Unexpected type errors with bytes and typing.ByteString #4871

@ericnorris

Description

@ericnorris

I've run into some issues when using bytes or typing.ByteString as a way to annotate arguments and return types that are able to be bytes, bytearray, or memoryview.

Per the docs:

class typing.ByteString(Sequence[int])
A generic version of collections.abc.ByteString.

This type represents the types bytes, bytearray, and memoryview.

As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.

I've included some code and output below that, at least to me, is unexpected given the above documentation.

Code:

from typing import ByteString


def bytestring_test(param: ByteString) -> ByteString:
    return param[1:3]


def bytes_test(param: bytes) -> bytes:
    return param[1:3]


def main() -> None:
    data = b"meowmeow"
    view = memoryview(data)

    bytestring_test(data)
    bytestring_test(view)

    bytes_test(data)
    bytes_test(view)


if __name__ == '__main__':
    main()

Output:

$ mypy test.py
test.py:4: error: Incompatible return value type (got "Sequence[int]", expected "ByteString")
test.py:16: error: Argument 1 to "bytestring_test" has incompatible type "memoryview"; expected "ByteString"
test.py:19: error: Argument 1 to "bytes_test" has incompatible type "memoryview"; expected "bytes"

I expect there to be no type errors at all, but please correct me if my understanding is flawed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions