Skip to content

Commit c4f3895

Browse files
authored
DOCSP-46812 - Distribute Type Hints (#167)
1 parent 4188490 commit c4f3895

File tree

15 files changed

+536
-455
lines changed

15 files changed

+536
-455
lines changed

source/aggregation/aggregation-tutorials/filtered-subset.txt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,7 @@ Tutorial
9090
Next, add a :manual:`$sort
9191
</reference/operator/aggregation/sort>` stage that sorts the
9292
documents in descending order by the ``dateofbirth`` field to
93-
list the youngest people first. Because Python dictionaries don't maintain the
94-
order of their elements, use a ``SON``or ``OrderedDict`` object
95-
instead:
93+
list the youngest people first:
9694

9795
.. literalinclude:: /includes/aggregation/filtered-subset.py
9896
:language: python

source/connect/mongoclient.txt

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ constructor accepts. All parameters are optional.
119119
:wikipedia:`round-robin DNS <Round-robin_DNS>` addresses.
120120

121121
**Data type:** ``Union[str, Sequence[str]]``
122-
**Default value:** ``"localhost"``
122+
| **Default value:** ``"localhost"``
123123

124124
* - ``port``
125125
- The port number {+mdb-server+} is running on.
@@ -128,17 +128,35 @@ constructor accepts. All parameters are optional.
128128
instead of using this parameter.
129129

130130
**Data type:** ``int``
131-
**Default value:** ``27017``
131+
| **Default value:** ``27017``
132132

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

138-
If you specify ``bson.son.SON`` as the document class, you must also specify types
139-
for the key and value.
137+
- ``bson.raw_bson.RawBSONDocument``. To learn more about the ``RawBSONDocument`` class,
138+
see :ref:`pymongo-bson-raw`.
139+
140+
- A subclass of the ``collections.abc.Mapping`` type, such as ``OrderedDict``.
141+
Depending on the strictness of your type-checking rules, you might also need to
142+
specify types for the key and value, as shown in the following example:
143+
144+
.. code-block:: python
145+
146+
client = MongoClient(document_class=OrderedDict[str, int])
147+
148+
- A subclass of the ``TypedDict`` type. To pass a ``TypedDict`` subclass for this
149+
parameter, you must also include the class in a type hint for your ``MongoClient``
150+
object, as shown in the following example:
151+
152+
.. code-block:: python
153+
154+
client: MongoClient[MyTypedDict] = MongoClient()
155+
156+
.. include:: /includes/type-hints/typeddict-availability.rst
140157

141158
**Data type:** ``Type[_DocumentType]``
159+
**Default:** ``dict``
142160

143161
* - ``tz_aware``
144162
- If this parameter is ``True``, the client treats ``datetime`` values as aware.
@@ -231,28 +249,46 @@ To use multiprocessing with {+driver-short+}, write code similar to the followin
231249
Do not copy an instance of the ``MongoClient`` class from the parent process to a child
232250
process.
233251

234-
Type Hints
252+
.. _pymongo-type-hints-client:
253+
254+
Type Hints
235255
----------
236256

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

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

242262
.. code-block:: python
243263

244264
client: MongoClient = MongoClient()
245265

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

251270
.. code-block:: python
252271

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

275+
If all the documents that you are working with correspond to a single custom type, you
276+
can specify the custom type as a type hint for your ``MongoClient`` object. This
277+
provides more accurate type information than the generic ``Dict[str, Any]`` type.
278+
279+
The following example shows how to specify the ``Movie`` type as a type hint for a
280+
``MongoClient`` object:
281+
282+
.. code-block:: python
283+
284+
from typing import TypedDict
285+
286+
class Movie(TypedDict):
287+
name: str
288+
year: int
289+
290+
client: MongoClient[Movie] = MongoClient()
291+
256292
Troubleshooting
257293
---------------
258294

@@ -317,10 +353,14 @@ process.
317353
multithreaded contexts with ``fork()``, see `Issue 6721 <http://bugs.python.org/issue6721>`__
318354
in the Python Issue Tracker.
319355

356+
.. include:: /includes/type-hints/troubleshooting-client-type.rst
357+
358+
.. include:: /includes/type-hints/troubleshooting-incompatible-type.rst
359+
320360
API Documentation
321361
-----------------
322362

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

326-
- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__
366+
- `MongoClient <{+api-root+}pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__

source/data-formats/bson.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ The following example reads the sample BSON document from ``file.bson``:
117117

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

120+
.. _pymongo-bson-raw:
121+
120122
Work with Raw BSON Data
121123
-----------------------
122124

source/databases-collections.txt

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,9 +321,79 @@ To learn more about supported retryable read operations, see :manual:`Retryable
321321
in the {+mdb-server+} manual. To learn more about supported retryable write
322322
operations, see :manual:`Retryable Writes </core/retryable-writes/>` in the {+mdb-server+} manual.
323323

324+
.. _pymongo-databases-collection-type-hints:
325+
326+
Type Hints
327+
----------
328+
329+
.. include:: /includes/type-hints/intro.rst
330+
331+
.. note:: TypedDict in Python 3.7 and Earlier
332+
333+
.. include:: /includes/type-hints/typeddict-availability.rst
334+
335+
Database
336+
~~~~~~~~
337+
338+
If all documents in a database match a well-defined schema, you can specify a type hint
339+
that uses a Python class to represent the documents' structure. By including this class
340+
in the type hint for your ``Database`` object, you can ensure that all documents you
341+
store or retrieve have the required structure. This provides more accurate type
342+
checking and code completion than the default ``Dict[str, Any]`` type.
343+
344+
First, define a class to represent a document from the database. The class must inherit
345+
from the ``TypedDict`` class and must contain the same fields as the documents in the
346+
database. After you define your class, include its name as the generic type for the
347+
``Database`` type hint.
348+
349+
The following example defines a ``Movie`` class and uses it as the
350+
generic type for a ``Database`` type hint:
351+
352+
.. code-block:: python
353+
:emphasize-lines: 5-7, 10
354+
355+
from typing import TypedDict
356+
from pymongo import MongoClient
357+
from pymongo.database import Database
358+
359+
class Movie(TypedDict):
360+
name: str
361+
year: int
362+
363+
client: MongoClient = MongoClient()
364+
database: Database[Movie] = client["test_database"]
365+
366+
Collection
367+
~~~~~~~~~~
368+
369+
Adding a generic type to a ``Collection`` type hint is similar to adding a generic type
370+
to a ``Database`` type hint. First, define a class that inherits from the ``TypedDict`` class
371+
and represents the structure of the
372+
documents in the collection. Then, include the class name as the generic type for the
373+
``Collection`` type hint, as shown in the following example:
374+
375+
.. code-block:: python
376+
:emphasize-lines: 5-7,11
377+
378+
from typing import TypedDict
379+
from pymongo import MongoClient
380+
from pymongo.collection import Collection
381+
382+
class Movie(TypedDict):
383+
name: str
384+
year: int
385+
386+
client: MongoClient = MongoClient()
387+
database = client["test_database"]
388+
collection: Collection[Movie] = database["test_collection"]
389+
324390
Troubleshooting
325391
---------------
326392

393+
.. include:: /includes/type-hints/troubleshooting-client-type.rst
394+
395+
.. include:: /includes/type-hints/troubleshooting-incompatible-type.rst
396+
327397
.. include:: /includes/troubleshooting/read-write-options.rst
328398

329399
API Documentation

0 commit comments

Comments
 (0)