Add zero-copy conversion of `bytearray` to `bytes` by providing `__bytes__()`

This might work, but only in one direction. In BytesIO it works in two directions – when you create a BytesIO from a bytes object it does not copy the data, but keep a reference for an existing bytes object, and getvalue() returns the internal bytes object (truncating it if possible).

The “moving constructor” would be useful in many other cases – for example when you create tuple from a list or frozenset from a set and throw away the original list or set. But it is dificult to came with solution which would not look like preliminary optimization.

5 Likes