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

Specifying a generic type for a collection does not correctly enforce type safety when inserting data

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 4.3.3
    • Affects Version/s: 4.2
    • Component/s: Typing
    • None

      When I attempt to use type hints to ensure the type safety of my operations, I get errors whenever I attempt to insert a TypedDict into my database.

      Refer to this documentation

       

      class Person(TypedDict):
          name: str
          age: int 
      
      client = MongoClient("...")
      collection: Collection[Person] = client.test_database.my_collection
      
      val = collection.insert_one(Person({"name": "Harold", "age": 15}))
      # Argument 1 to "insert_one" of "Collection" has incompatible type 
      # "Person"; expected "Union[MutableMapping[str, Any], RawBSONDocument]"

      I have also noticed that no type checks are performed on inserted data.

      val = collection.insert_one({"name": 17, "age": "this isn't a number", "gender": 6}) 

      Even though all the parameter types are incorrect, no checks are performed to ensure their validity and I receive no errors.

      How can I type check data that I insert to a collection?

       

            Assignee:
            julius.park@mongodb.com Julius Park (Inactive)
            Reporter:
            miguelag2001@outlook.com Miguel Guthridge
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: