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.
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).