From 5dd6ffbbb8ce3b4959dee71518a23e4f4d585b14 Mon Sep 17 00:00:00 2001 From: Shane Harvey Date: Wed, 12 Jun 2024 11:02:19 -0700 Subject: [PATCH] PYTHON-4347 Improve performance by only calling get_topology once (#1673) --- pymongo/asynchronous/mongo_client.py | 9 ++++++--- pymongo/synchronous/mongo_client.py | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index 8319755d0..2f13b92c6 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -854,6 +854,7 @@ class AsyncMongoClient(common.BaseObject, Generic[_DocumentType]): server_monitoring_mode=options.server_monitoring_mode, ) + self._opened = False self._init_background() if _IS_SYNC and connect: @@ -1528,9 +1529,11 @@ class AsyncMongoClient(common.BaseObject, Generic[_DocumentType]): If this client was created with "connect=False", calling _get_topology launches the connection process in the background. """ - await self._topology.open() - async with self._lock: - self._kill_cursors_executor.open() + if not self._opened: + await self._topology.open() + async with self._lock: + self._kill_cursors_executor.open() + self._opened = True return self._topology @contextlib.asynccontextmanager diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index 69bfa7a9d..20d1b3f82 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -853,6 +853,7 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]): server_monitoring_mode=options.server_monitoring_mode, ) + self._opened = False self._init_background() if _IS_SYNC and connect: @@ -1527,9 +1528,11 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]): If this client was created with "connect=False", calling _get_topology launches the connection process in the background. """ - self._topology.open() - with self._lock: - self._kill_cursors_executor.open() + if not self._opened: + self._topology.open() + with self._lock: + self._kill_cursors_executor.open() + self._opened = True return self._topology @contextlib.contextmanager