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

Mapping is not an acceptable return type for bson.decode

      My initial annotations for bson/pymongo use Mapping as the document type. For example, bson.decode:

      def decode(data: bytes, codec_options: CodecOptions = ...) -> Mapping[str, Any]: ...
      

      Unfortunately, this is not sufficient as it breaks this simple (and correct) code which attempts to mutate the dict returned by bson.decode:

      $ cat repro-PYTHON-2427.py   
      import bson
      bson_bytes = bson.encode({})
      doc = bson.decode(bson_bytes)
      doc['mutable'] = True
      print(doc)
      $ python repro-PYTHON-2427.py
      {'mutable': True}
      $ mypy repro-PYTHON-2427.py 
      repro-PYTHON-2427.py:4: error: Unsupported target for indexed assignment ("Mapping[str, Any]")
      Found 1 error in 1 file (checked 1 source file)
      

      Some solutions to this problem:

      • Make CodecOptions generic such that we return the document_class of the passed in CodecOptions. Initial attempts of this have been fruitless as NamedTuple and Generic do not play nice together.
      • Annotate returned BSON documents with Any. This avoids the false positive described above but is annoyingly vague. Perhaps this is the best we can do for now though.

            Assignee:
            shane.harvey@mongodb.com Shane Harvey
            Reporter:
            shane.harvey@mongodb.com Shane Harvey
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: