# Add zero-copy conversion of \`bytearray\` to \`bytes\` by providing \`\_\_bytes\_\_()\`

**URL:** <https://discuss.python.org/t/add-zero-copy-conversion-of-bytearray-to-bytes-by-providing-bytes/79164>\
**Category:** Ideas\
**Tags:** performance\
**Created:** [February 2, 2025, 4:25am UTC](https://discuss.python.org/t/add-zero-copy-conversion-of-bytearray-to-bytes-by-providing-bytes/79164 "2025-02-02T04:25:16Z")\
**Posts on this page:** 1\
**Showing post:** 15

<div class="post-metadata">

**Author:** ![storchaka](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/storchaka/32/217_2.png) [@storchaka](https://discuss.python.org/u/storchaka)\
**Post date:** [February 3, 2025, 12:54pm UTC](https://discuss.python.org/t/add-zero-copy-conversion-of-bytearray-to-bytes-by-providing-bytes/79164/15 "2025-02-03T12:54:09Z")

</div>

I was thinking about this idea. This is actually how `BytesIO` is implemented.

But what if the original `bytearray` is changed after creating a `bytes`? You need to check if there are external references to the internal `bytes` buffer (i.e. if the references count is larger than 1) before every mutable operation. You can do this for Python interface, this will add some overhead, but it may be tolerable. But in the C API there is `PyByteArray_AS_STRING()`. You cannot catch mutation of the memory array returned by `PyByteArray_AS_STRING()`. And it is not possible to make a copy in `PyByteArray_AS_STRING()`, because this C API never fails, so the users never check it for errors. The only way is to deprecate and finally remove `PyByteArray_AS_STRING()`, but this is too serios change.

---

_[View the full topic](https://discuss.python.org/t/add-zero-copy-conversion-of-bytearray-to-bytes-by-providing-bytes/79164)._
