I recently revised PEP 688 (
https://peps.python.org/pep-0688/), which proposes a mechanism to make the buffer protocol accessible to the type system. The most technically challenging part of the PEP is in the interaction with the C API, so I opened a primary discussion thread on the core dev Discourse at
https://discuss.python.org/t/pep-688-take-2-making-the-buffer-protocol-accessible-in-python/19756.
However, the PEP also proposes a change that affects primarily static type checkers: removing the implicit promotion of memoryview and bytearray to bytes. For context, the CPython docs currently specify that a type annotation of "bytes" should also include bytearray and memoryview values, similar to how "float" implicitly includes int. Mypy and pyright implement this rule; pyre does not.
I have a draft mypy PR removing the implicit promotion at
https://github.com/python/mypy/pull/12661. The mypy-primer output shows that it is not uncommon for projects to rely on the implicit promotion. (Though it's worth noting that a maintainer of the most impacted project, psycopg, asked mypy to remove the implicit promotion because it caused mypy to miss bugs:
https://github.com/python/mypy/issues/12643#issuecomment-1105914159.) Several people commented on Discourse that they feel it is more intuitive for newcomers if a bytes type annotation also includes bytearray.
The more I think about it, the more I'm convinced that it's better in the long term to remove this implicit promotion. The most basic rule in Python typing is that if you put a type X in an annotation, only instances of that type are accepted. Exceptions to that rule are counterintuitive and lead to confusing edge cases. If you want either bytes or bytearray, you should write "bytes | bytearray"; if you want just bytes, you should write "bytes".
But I'm willing to change the PEP if the consensus in the typing community is that it's better to keep the implicit bytes/bytearray promotion. What do you think?
I'm less willing to keep accepting memoryview as compatible with bytes. bytearray really does have almost perfect interoperability with bytes (the main exception is that it's not hashable), but memoryview has little in common with bytes beyond being a buffer.