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

Binary should accept memoryviews/buffer objects

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor - P4
    • Resolution: Fixed
    • None
    • 3.9
    • BSON
    • None
    • Any Python
    • Fully Compatible

    Description

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

       

      Attachments

        Issue Links

          Activity

            People

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

              Dates

                Created:
                Updated:
                Resolved: