Skip to content

DOCSP-46812 - Distribute Type Hints #167

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions source/aggregation/aggregation-tutorials/filtered-subset.txt
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ Tutorial
Next, add a :manual:`$sort
</reference/operator/aggregation/sort>` stage that sorts the
documents in descending order by the ``dateofbirth`` field to
list the youngest people first. Because Python dictionaries don't maintain the
order of their elements, use a ``SON``or ``OrderedDict`` object
instead:
list the youngest people first:

.. literalinclude:: /includes/aggregation/filtered-subset.py
:language: python
Expand Down
70 changes: 55 additions & 15 deletions source/connect/mongoclient.txt
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
:wikipedia:`round-robin DNS <Round-robin_DNS>` addresses.

**Data type:** ``Union[str, Sequence[str]]``
**Default value:** ``"localhost"``
| **Default value:** ``"localhost"``

* - ``port``
- The port number {+mdb-server+} is running on.
Expand All @@ -128,17 +128,35 @@
instead of using this parameter.

**Data type:** ``int``
**Default value:** ``27017``
| **Default value:** ``27017``

* - ``document_class``
- The default class that the client uses to decode BSON documents returned by queries.
This parameter supports the ``bson.raw_bson.RawBSONDocument`` type, as well as
subclasses of the ``collections.abc.Mapping`` type, such as ``bson.son.SON``.
This parameter accepts the following types:

If you specify ``bson.son.SON`` as the document class, you must also specify types
for the key and value.
- ``bson.raw_bson.RawBSONDocument``. To learn more about the ``RawBSONDocument`` class,
see :ref:`pymongo-bson-raw`.

- A subclass of the ``collections.abc.Mapping`` type, such as ``OrderedDict``.
Depending on the strictness of your type-checking rules, you might also need to

Check failure on line 141 in source/connect/mongoclient.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'must' is preferred over 'need to'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'must' is preferred over 'need to'.", "location": {"path": "source/connect/mongoclient.txt", "range": {"start": {"line": 141, "column": 82}}}, "severity": "ERROR"}
specify types for the key and value, as shown in the following example:

.. code-block:: python

client = MongoClient(document_class=OrderedDict[str, int])

- A subclass of the ``TypedDict`` type. To pass a ``TypedDict`` subclass for this
parameter, you must also include the class in a type hint for your ``MongoClient``
object, as shown in the following example:

.. code-block:: python

client: MongoClient[MyTypedDict] = MongoClient()

.. include:: /includes/type-hints/typeddict-availability.rst

**Data type:** ``Type[_DocumentType]``
**Default:** ``dict``

* - ``tz_aware``
- If this parameter is ``True``, the client treats ``datetime`` values as aware.
Expand Down Expand Up @@ -226,28 +244,46 @@
Do not copy an instance of the ``MongoClient`` class from the parent process to a child
process.

Type Hints
.. _pymongo-type-hints-client:

Type Hints
----------

If you're using Python v3.5 or later, you can add type hints to your Python code.
.. include:: /includes/type-hints/intro.rst

The following code example shows how to declare a type hint for a ``MongoClient``
object:
To use type hints in your {+driver-short+} application, you must add a type annotation to your
``MongoClient`` object, as shown in the following example:

.. code-block:: python

client: MongoClient = MongoClient()

In the previous example, the code doesn't specify a type for the documents that the
``MongoClient`` object will work with. To specify a document type,
include the ``Dict[str, Any]`` type when you
create the ``MongoClient`` object, as shown in the following example:
For more accurate type information, you can include the generic document type
``Dict[str, Any]`` in your type annotation. This data type matches all documents in MongoDB.
The following example shows how to include this data type in your type annotation:

.. code-block:: python

from typing import Any, Dict
client: MongoClient[Dict[str, Any]] = MongoClient()

If all the documents that you are working with correspond to a single custom type, you
can specify the custom type as a type hint for your ``MongoClient`` object. This
provides more accurate type information than the generic ``Dict[str, Any]`` type.

The following example shows how to specify the ``Movie`` type as a type hint for a

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add the definition of Movie here for clarity.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

happy to!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still missing the Movie definition here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoops

``MongoClient`` object:

.. code-block:: python

from typing import TypedDict

class Movie(TypedDict):
name: str
year: int

client: MongoClient[Movie] = MongoClient()

Troubleshooting
---------------

Expand Down Expand Up @@ -312,10 +348,14 @@
multithreaded contexts with ``fork()``, see `Issue 6721 <http://bugs.python.org/issue6721>`__
in the Python Issue Tracker.

.. include:: /includes/type-hints/troubleshooting-client-type.rst

.. include:: /includes/type-hints/troubleshooting-incompatible-type.rst

API Documentation
-----------------

To learn more about creating a ``MongoClient`` object in {+driver-short+},
see the following API documentation:

- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__
- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__
2 changes: 2 additions & 0 deletions source/data-formats/bson.txt
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ The following example reads the sample BSON document from ``file.bson``:

{"address": {"street": "Pizza St", "zipcode": "10003"}, "coord": [-73.982419, 41.579505], "cuisine": "Pizza", "name": "Mongo's Pizza"}

.. _pymongo-bson-raw:

Work with Raw BSON Data
-----------------------

Expand Down
70 changes: 70 additions & 0 deletions source/databases-collections.txt
Original file line number Diff line number Diff line change
Expand Up @@ -321,9 +321,79 @@ To learn more about supported retryable read operations, see :manual:`Retryable
in the {+mdb-server+} manual. To learn more about supported retryable write
operations, see :manual:`Retryable Writes </core/retryable-writes/>` in the {+mdb-server+} manual.

.. _pymongo-databases-collection-type-hints:

Type Hints
----------

.. include:: /includes/type-hints/intro.rst

.. note:: TypedDict in Python 3.7 and Earlier

.. include:: /includes/type-hints/typeddict-availability.rst

Database
~~~~~~~~

If all documents in a database match a well-defined schema, you can specify a type hint
that uses a Python class to represent the documents' structure. By including this class
in the type hint for your ``Database`` object, you can ensure that all documents you
store or retrieve have the required structure. This provides more accurate type
checking and code completion than the default ``Dict[str, Any]`` type.

First, define a class to represent a document from the database. The class must inherit
from the ``TypedDict`` class and must contain the same fields as the documents in the
database. After you define your class, include its name as the generic type for the
``Database`` type hint.

The following example defines a ``Movie`` class and uses it as the
generic type for a ``Database`` type hint:

.. code-block:: python
:emphasize-lines: 5-7, 10

from typing import TypedDict
from pymongo import MongoClient
from pymongo.database import Database

class Movie(TypedDict):
name: str
year: int

client: MongoClient = MongoClient()
database: Database[Movie] = client["test_database"]

Collection
~~~~~~~~~~

Adding a generic type to a ``Collection`` type hint is similar to adding a generic type
to a ``Database`` type hint. First, define a class that inherits from the ``TypedDict`` class
and represents the structure of the
documents in the collection. Then, include the class name as the generic type for the
``Collection`` type hint, as shown in the following example:

.. code-block:: python
:emphasize-lines: 5-7,11

from typing import TypedDict
from pymongo import MongoClient
from pymongo.collection import Collection

class Movie(TypedDict):
name: str
year: int

client: MongoClient = MongoClient()
database = client["test_database"]
collection: Collection[Movie] = database["test_collection"]

Troubleshooting
---------------

.. include:: /includes/type-hints/troubleshooting-client-type.rst

.. include:: /includes/type-hints/troubleshooting-incompatible-type.rst

.. include:: /includes/troubleshooting/read-write-options.rst

API Documentation
Expand Down
Loading
Loading