@@ -56,19 +56,40 @@ Serializing Custom Classes
5656
5757To serialize a custom class, you must convert the class to a dictionary. The following
5858example serializes a custom class by using the ``vars()`` method, and then inserts the
59- serialized object into a collection:
59+ serialized object into a collection. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous`
60+ tab to see the corresponding code:
6061
61- .. code-block:: python
62+ .. tabs::
63+
64+ .. tab:: Synchronous
65+ :tabid: sync
66+
67+ .. code-block:: python
68+
69+ class Restaurant:
70+ def __init__(self, name, cuisine):
71+ self.name = name
72+ self.cuisine = cuisine
73+
74+ restaurant = Restaurant("Example Cafe", "Coffee")
75+ restaurant_dict = vars(restaurant)
76+
77+ collection.insert_one(restaurant_dict)
78+
79+ .. tab:: Asynchronous
80+ :tabid: async
6281
63- class Restaurant:
64- def __init__(self, name, cuisine):
65- self.name = name
66- self.cuisine = cuisine
82+ .. code-block:: python
6783
68- restaurant = Restaurant("Example Cafe", "Coffee")
69- restaurant_dict = vars(restaurant)
84+ class Restaurant:
85+ def __init__(self, name, cuisine):
86+ self.name = name
87+ self.cuisine = cuisine
88+
89+ restaurant = Restaurant("Example Cafe", "Coffee")
90+ restaurant_dict = vars(restaurant)
7091
71- collection.insert_one(restaurant_dict)
92+ await collection.insert_one(restaurant_dict)
7293
7394The preceding example serializes the ``Restaurant`` object into the following dictionary:
7495
@@ -84,15 +105,29 @@ Deserializing Custom Classes
84105
85106To deserialize a custom class, you must convert the dictionary back into an instance of
86107the class. The following example retrieves a document from a collection, and then converts
87- it back into a ``Restaurant`` object from the preceding example:
108+ it back into a ``Restaurant`` object from the preceding example. Select the
109+ :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code:
110+
111+ .. tabs::
112+
113+ .. tab:: Synchronous
114+ :tabid: sync
115+
116+ .. code-block:: python
117+
118+ def deserialize_restaurant(doc):
119+ return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
120+
121+ .. tab:: Asynchronous
122+ :tabid: async
88123
89- .. code-block:: python
124+ .. code-block:: python
90125
91- def deserialize_restaurant(doc):
92- return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
126+ def deserialize_restaurant(doc):
127+ return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
93128
94- restaurant_doc = collection.find_one({"name": "Example Cafe"})
95- restaurant = deserialize_restaurant(restaurant_doc)
129+ restaurant_doc = await collection.find_one({"name": "Example Cafe"})
130+ restaurant = deserialize_restaurant(restaurant_doc)
96131
97132To learn more about retrieving documents from a collection, see the :ref:`pymongo-retrieve`
98133guide.
0 commit comments