From 6b9c9568bac8bde9c3b0e9c7b1fac6dc941c0eff Mon Sep 17 00:00:00 2001 From: Abhiraj Adhikary Date: Fri, 27 Nov 2026 04:45:29 +0530 Subject: [PATCH 1/2] feat(client): add close and context manager support to Client and AsyncClient --- src/typesense/async_/client.py | 18 +++++++++++ src/typesense/sync/client.py | 18 +++++++++++ tests/client_test.py | 59 ++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) diff --git a/src/typesense/async_/client.py b/src/typesense/async_/client.py index 49338b61..0f0e5d30 100644 --- a/src/typesense/async_/client.py +++ b/src/typesense/async_/client.py @@ -27,6 +27,7 @@ """ import sys +from types import TracebackType from typing_extensions import deprecated @@ -135,6 +136,23 @@ def __init__( self.conversations_models = AsyncConversationsModels(self.api_call) self.nl_search_models = AsyncNLSearchModels(self.api_call) + async def __aenter__(self) -> "AsyncClient": + """Enter the context manager.""" + return self + + async def __aexit__( + self, + exc_type: typing.Optional[typing.Type[BaseException]], + exc_val: typing.Optional[BaseException], + exc_tb: typing.Optional[TracebackType], + ) -> None: + """Exit the context manager and close the HTTP client.""" + await self.aclose() + + async def aclose(self) -> None: + """Close the underlying HTTP client, unless it was passed in by the caller.""" + await self.api_call.aclose() + @property @deprecated( "AnalyticsV1 is deprecated on v30+. Use client.analytics instead.", diff --git a/src/typesense/sync/client.py b/src/typesense/sync/client.py index 6343904c..a7077cd3 100644 --- a/src/typesense/sync/client.py +++ b/src/typesense/sync/client.py @@ -27,6 +27,7 @@ """ import sys +from types import TracebackType from typing_extensions import deprecated @@ -135,6 +136,23 @@ def __init__( self.conversations_models = ConversationsModels(self.api_call) self.nl_search_models = NLSearchModels(self.api_call) + def __enter__(self) -> "Client": + """Enter the context manager.""" + return self + + def __exit__( + self, + exc_type: typing.Optional[typing.Type[BaseException]], + exc_val: typing.Optional[BaseException], + exc_tb: typing.Optional[TracebackType], + ) -> None: + """Exit the context manager and close the HTTP client.""" + self.close() + + def close(self) -> None: + """Close the underlying HTTP client, unless it was passed in by the caller.""" + self.api_call.close() + @property @deprecated( "AnalyticsV1 is deprecated on v30+. Use client.analytics instead.", diff --git a/tests/client_test.py b/tests/client_test.py index ffff3a44..39bf4904 100644 --- a/tests/client_test.py +++ b/tests/client_test.py @@ -1,7 +1,10 @@ """Tests for the Client class.""" +import httpx + from tests.fixtures.document_fixtures import Companies from tests.utils.object_assertions import assert_match_object, assert_object_lists_match +from typesense.async_.client import AsyncClient from typesense.sync.client import Client from typesense.configuration import ConfigDict @@ -72,3 +75,59 @@ def test_retrieve_collection_actual_no_name( collection = actual_client.typed_collection(model=Companies) assert collection is not None + + +def test_client_close(fake_config_dict: ConfigDict) -> None: + """Test that Client.close closes an owned HTTP client.""" + client = Client(fake_config_dict) + assert client.api_call._client.is_closed is False + client.close() + assert client.api_call._client.is_closed is True + + +def test_client_context_manager(fake_config_dict: ConfigDict) -> None: + """Test that Client closes its HTTP client when used as a context manager.""" + with Client(fake_config_dict) as client: + assert client.api_call._client.is_closed is False + assert client.api_call._client.is_closed is True + + +def test_client_does_not_close_external_http_client( + fake_config_dict: ConfigDict, +) -> None: + """Test that Client.close does not close a caller-supplied http_client.""" + external_client = httpx.Client() + try: + with Client(fake_config_dict, http_client=external_client) as client: + assert client.api_call._client is external_client + assert external_client.is_closed is False + finally: + external_client.close() + + +async def test_async_client_aclose(fake_config_dict: ConfigDict) -> None: + """Test that AsyncClient.aclose closes an owned HTTP client.""" + client = AsyncClient(fake_config_dict) + assert client.api_call._client.is_closed is False + await client.aclose() + assert client.api_call._client.is_closed is True + + +async def test_async_client_context_manager(fake_config_dict: ConfigDict) -> None: + """Test that AsyncClient closes its HTTP client when used as an async context manager.""" + async with AsyncClient(fake_config_dict) as client: + assert client.api_call._client.is_closed is False + assert client.api_call._client.is_closed is True + + +async def test_async_client_does_not_close_external_http_client( + fake_config_dict: ConfigDict, +) -> None: + """Test that AsyncClient.aclose does not close a caller-supplied http_client.""" + external_client = httpx.AsyncClient() + try: + async with AsyncClient(fake_config_dict, http_client=external_client) as client: + assert client.api_call._client is external_client + assert external_client.is_closed is False + finally: + await external_client.aclose() From 77ec0399d66b95f159078b14263aa434bd8d0f1d Mon Sep 17 00:00:00 2001 From: Abhiraj Adhikary Date: Fri, 27 Nov 2026 15:07:05 +0530 Subject: [PATCH 2/2] docs(client): use context manager in examples and return typing.Self from __enter__/__aenter__ --- README.md | 10 ++-- examples/async_collection_operations.py | 8 +-- examples/async_conversation_streaming.py | 8 +-- examples/async_export_streaming.py | 68 ++++++++++++------------ src/typesense/async_/client.py | 2 +- src/typesense/sync/client.py | 2 +- 6 files changed, 43 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index e9b97fce..ee3f8a89 100644 --- a/README.md +++ b/README.md @@ -26,21 +26,19 @@ import typesense async def main() -> None: - client = typesense.AsyncClient({ + async with typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, - }) - - print(await client.collections.retrieve()) - await client.api_call.aclose() + }) as client: + print(await client.collections.retrieve()) if __name__ == "__main__": asyncio.run(main()) ``` -See `examples/async_collection_operations.py` for a fuller async walkthrough. +See `examples/async_collection_operations.py` for a fuller async walkthrough. Note that if you pass a caller-supplied `http_client`, `AsyncClient` (and `Client`) leaves it open when exiting the context manager or calling `aclose()`/`close()`, so you are responsible for closing it. ## Streaming document exports diff --git a/examples/async_collection_operations.py b/examples/async_collection_operations.py index c4d86351..1f7aca08 100644 --- a/examples/async_collection_operations.py +++ b/examples/async_collection_operations.py @@ -12,7 +12,7 @@ async def main() -> None: - client = typesense.AsyncClient( + async with typesense.AsyncClient( { "api_key": "xyz", "nodes": [ @@ -24,9 +24,7 @@ async def main() -> None: ], "connection_timeout_seconds": 2, } - ) - - try: + ) as client: # Drop pre-existing collection if any try: await client.collections["books"].delete() @@ -188,8 +186,6 @@ async def main() -> None: # Drop the collection drop_response = await client.collections["books"].delete() print(drop_response) - finally: - await client.api_call.aclose() if __name__ == "__main__": diff --git a/examples/async_conversation_streaming.py b/examples/async_conversation_streaming.py index af682df0..29786ac2 100644 --- a/examples/async_conversation_streaming.py +++ b/examples/async_conversation_streaming.py @@ -33,7 +33,7 @@ async def main() -> None: documents_collection = f"streaming_docs_{run_id}" model_id = f"streaming_model_{run_id}" - client = typesense.AsyncClient( + async with typesense.AsyncClient( { "api_key": typesense_api_key, "nodes": [ @@ -45,9 +45,7 @@ async def main() -> None: ], "connection_timeout_seconds": 10, } - ) - - try: + ) as client: await client.collections.create( { "name": history_collection, @@ -139,8 +137,6 @@ def on_complete(response: SearchResponse[typing.Any]) -> None: "stream_config": stream_config, } ) - finally: - await client.api_call.aclose() if __name__ == "__main__": diff --git a/examples/async_export_streaming.py b/examples/async_export_streaming.py index 93752b59..25c97cb3 100644 --- a/examples/async_export_streaming.py +++ b/examples/async_export_streaming.py @@ -13,48 +13,46 @@ async def main() -> None: - client = typesense.AsyncClient( + async with typesense.AsyncClient( { "api_key": os.environ.get("TYPESENSE_API_KEY", "xyz"), "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 10, } - ) - - await client.collections.create( - { - "name": COLLECTION, - "fields": [ - {"name": "title", "type": "string"}, - {"name": "year", "type": "int32"}, - ], - } - ) - - try: - documents = client.collections[COLLECTION].documents - await documents.import_( - [{"id": str(year), "title": f"Book {year}", "year": year} for year in range(2000, 2010)], - {"action": "create"}, + ) as client: + await client.collections.create( + { + "name": COLLECTION, + "fields": [ + {"name": "title", "type": "string"}, + {"name": "year", "type": "int32"}, + ], + } ) - # Read one document at a time. The stream is closed when the block ends, - # even if the loop stops early. - async with await documents.export_stream( - {"filter_by": "year:>=2005", "batch_size": 100}, - ) as stream: - async for line in stream: - print(json.loads(line)["title"]) - - # Count the bytes without keeping the export in memory. - size = 0 - async with await documents.export_stream() as stream: - async for chunk in stream.aiter_bytes(): - size += len(chunk) - print(f"Read {size} bytes") - finally: - await client.collections[COLLECTION].delete() - await client.api_call.aclose() + try: + documents = client.collections[COLLECTION].documents + await documents.import_( + [{"id": str(year), "title": f"Book {year}", "year": year} for year in range(2000, 2010)], + {"action": "create"}, + ) + + # Read one document at a time. The stream is closed when the block ends, + # even if the loop stops early. + async with await documents.export_stream( + {"filter_by": "year:>=2005", "batch_size": 100}, + ) as stream: + async for line in stream: + print(json.loads(line)["title"]) + + # Count the bytes without keeping the export in memory. + size = 0 + async with await documents.export_stream() as stream: + async for chunk in stream.aiter_bytes(): + size += len(chunk) + print(f"Read {size} bytes") + finally: + await client.collections[COLLECTION].delete() if __name__ == "__main__": diff --git a/src/typesense/async_/client.py b/src/typesense/async_/client.py index 0f0e5d30..718f65af 100644 --- a/src/typesense/async_/client.py +++ b/src/typesense/async_/client.py @@ -136,7 +136,7 @@ def __init__( self.conversations_models = AsyncConversationsModels(self.api_call) self.nl_search_models = AsyncNLSearchModels(self.api_call) - async def __aenter__(self) -> "AsyncClient": + async def __aenter__(self) -> typing.Self: """Enter the context manager.""" return self diff --git a/src/typesense/sync/client.py b/src/typesense/sync/client.py index a7077cd3..d70a59f2 100644 --- a/src/typesense/sync/client.py +++ b/src/typesense/sync/client.py @@ -136,7 +136,7 @@ def __init__( self.conversations_models = ConversationsModels(self.api_call) self.nl_search_models = NLSearchModels(self.api_call) - def __enter__(self) -> "Client": + def __enter__(self) -> typing.Self: """Enter the context manager.""" return self