Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-1648

Binary should accept memoryviews/buffer objects

    • Type: Icon: New Feature New Feature
    • Resolution: Fixed
    • Priority: Icon: Minor - P4 Minor - P4
    • 3.9
    • Affects Version/s: None
    • Component/s: BSON
    • None
    • Environment:
      Any Python
    • Fully Compatible

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

       

            Assignee:
            bernie@mongodb.com Bernie Hackett
            Reporter:
            minrk Min RK
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: