Python has more than one type for representing binary data. It would be nice if bson.Binary constructor accepted any object providing the buffer-api.
One example of code that implements accepting any binary data type (including bytes):
def asbytes(obj):
return memoryview(obj).tobytes()
This is a much more flexible mechanism that takes any Python object that represents bytes, and accepts it as input. Additionally, a nice error is raised for objects that can't be cast to bytes:
TypeError: memoryview: a bytes-like object is required, not 'object'
It's possible that it would be even more efficient if the Binary object only stored the memoryview object, which would enable a potential reduction in memory copies by reading the memory directly, instead of reading a copy of the bytes. This might be slightly harder to maintain full backward-compatibility, though, since Binary is currently a subclass of `bytes`.
- is duplicated by
-
PYTHON-1825 Support encoding bytearray datatype as bson.Binary
- Closed
- is related to
-
PYTHON-1476 Flexible BSON Encoder/Decoder
- Released