Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the correct type annotation for "bytes or bytearray"?

In Python 3.11 or newer, is there a more convenient type annotation to use than bytes | bytearray for a function argument that means "An ordered collection of bytes"? It seems wasteful to require constructing a bytes from a bytearray (or the other way around) just to satisfy the type-checker.

Note that the function does not mutate the argument; it’s simply convenient to pass bytes or bytearray instances from different call sites.

e.g.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def serialize_to_stream(stream: MyStream, data: bytes | bytearray) -> None:
    for byte in data:
        stream.accumulate(byte)

(This example is contrived, of course, but the purpose is to show that data is only read, never mutated).

>Solution :

The typing module used to have a type to represent this: ByteString. However, it was deprecated in 3.9.

From the same section:

Prefer collections.abc.Buffer, or a union like bytes | bytearray | memoryview.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading