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

Support codec callbacks for simple types

    • Type: Icon: New Feature New Feature
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 3.8
    • Affects Version/s: None
    • Component/s: BSON
    • Labels:

      As part of the flexible BSON epic, we should implement support for registering callbacks to handle simple types that the bson module doesn't support natively.

      PYTHON-1731 provides a good example. PyMongo doesn't support decimal.Decimal, but does have a related type, decimal128.Decimal128. An application should be able to register a handler to automatically attempt conversion of Decimal to Decimal128. The callbacks could be defined something like this:

      # On encoding, the bson module calls the callback registered for a type
      # it doesn't natively support. That callback must return a type the bson
      # module does natively support, Decimal128 in this case.
      def decimal_to_decimal128(obj):
          return Decimal128(obj)
      # On decoding, the bson module decodes BSON data to a type it supports,
      # then calls the callback registered for that type. The callback can return any
      # type the application desires. In this example it returns a decimal.Decimal,
      def decimal128_to_decimal(obj):
          return obj.to_decimal()

      This would be a granular replacement for SON manipulators for simple types, where conversion is handled at the BSON layer. By comparison SON manipulators (which have been deprecated since PyMongo 3.0) require an application to iterate an entire document looking for types to convert, causing two full iterations of each document on encoding or decoding.

      This work should be extended to the json_util module as well.

      For complex types (for example, custom document models) PYTHON-1679 will provide far more flexibility to directly control BSON encoding (BSON writer) and decoding (BSON reader) than most applications require.

            prashant.mital Prashant Mital (Inactive)
            bernie@mongodb.com Bernie Hackett
            4 Vote for this issue
            6 Start watching this issue