Skip to content

Unexpected type errors with bytes and typing.ByteString #4871

Closed

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.

Activity

  1. gvanrossum commented on Apr 9, 2018

    @gvanrossum
    Member

    If you ask me, ByteString never really came off the ground. The code in the stdlib has a comment

        XXX Should add all their methods.
    

    The types.ByteString class is just an alias for collections.abc.ByteString, and it typeshed it's an empty subclass of Sequence[int].

    If you wanted to change all that you'd have to file issues on bugs.python.org and debate the merit.

    The proper way to type these things for mypy is to just use bytes -- mypy already treats bytearray as a virtual subclass of bytes. Probably it should do the same for memoryview (though it doesn't come up often enough to matter much in practice). See also python/typing#552

  2. ericnorris commented on Apr 9, 2018

    @ericnorris
    Author

    I'm fine with just using bytes, but as you noted it does not work with memoryview. I'll follow the progress on the other ticket. Thanks!

  3. added a commit that references this issue on May 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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