From 265ce4b2572f978465a43ecbfd59c540e44c00ec Mon Sep 17 00:00:00 2001 From: sumitsharma01 Date: Tue, 20 Oct 2026 14:46:56 +0200 Subject: [PATCH 1/3] feat: add client cleanup and context manager support --- README.md | 20 ++++----- codegen/templates/client.py.tmpl | 36 +++++++++++++++ sumup/_client.py | 36 +++++++++++++++ tests/test_client_lifecycle.py | 76 ++++++++++++++++++++++++++++++++ 4 files changed, 158 insertions(+), 10 deletions(-) create mode 100644 tests/test_client_lifecycle.py diff --git a/README.md b/README.md index 2112462f..e014848e 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,9 @@ import os from sumup import Sumup -client = Sumup(api_key="sup_sk_MvxmLOl0...") - -# Get merchant profile -merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) -print(f"Merchant: {merchant.merchant_code}") +with Sumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) + print(f"Merchant: {merchant.merchant_code}") ``` ### Async Client @@ -50,16 +48,18 @@ from sumup import AsyncSumup async def main(): - client = AsyncSumup(api_key="sup_sk_MvxmLOl0...") - - # Get merchant profile - merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) - print(f"Merchant: {merchant.merchant_code}") + async with AsyncSumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) + print(f"Merchant: {merchant.merchant_code}") asyncio.run(main()) ``` +Context managers close the client when the block exits, including when an exception occurs. +For long-running applications, reuse a client and call `client.close()` or +`await client.aclose()` during shutdown. + ### Creating a Checkout ```python diff --git a/codegen/templates/client.py.tmpl b/codegen/templates/client.py.tmpl index 550ae558..39e5a4ff 100644 --- a/codegen/templates/client.py.tmpl +++ b/codegen/templates/client.py.tmpl @@ -1,7 +1,9 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. import os +from types import TracebackType import typing import httpx +from typing_extensions import Self from ._service import Resource, AsyncResource, runtime_headers if typing.TYPE_CHECKING: @@ -42,6 +44,23 @@ class Sumup(Resource): }, )) + def close(self) -> None: + """Close the underlying HTTP client and release its connections.""" + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + self._client.__exit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, @@ -150,6 +169,23 @@ class AsyncSumup(AsyncResource): }, )) + async def aclose(self) -> None: + """Close the underlying HTTP client and release its connections.""" + await self._client.aclose() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + await self._client.__aexit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, diff --git a/sumup/_client.py b/sumup/_client.py index 4062972c..f174953a 100644 --- a/sumup/_client.py +++ b/sumup/_client.py @@ -1,8 +1,10 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. import os import typing +from types import TracebackType import httpx +from typing_extensions import Self from ._service import AsyncResource, Resource, runtime_headers @@ -60,6 +62,23 @@ def __init__( ) ) + def close(self) -> None: + """Close the underlying HTTP client and release its connections.""" + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + self._client.__exit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, @@ -233,6 +252,23 @@ def __init__( ) ) + async def aclose(self) -> None: + """Close the underlying HTTP client and release its connections.""" + await self._client.aclose() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + await self._client.__aexit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, diff --git a/tests/test_client_lifecycle.py b/tests/test_client_lifecycle.py new file mode 100644 index 00000000..b3b0dbad --- /dev/null +++ b/tests/test_client_lifecycle.py @@ -0,0 +1,76 @@ +import asyncio + +import httpx +import pytest + +from sumup import AsyncSumup, Sumup + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_explicit_close(use_async): + if use_async: + + async def run(): + client = AsyncSumup(api_key="test") + await client.aclose() + await client.aclose() + assert client._client.is_closed + + asyncio.run(run()) + else: + client = Sumup(api_key="test") + client.close() + client.close() + assert client._client.is_closed + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("raise_error", [False, True], ids=["success", "exception"]) +def test_context_manager_closes_transport(use_async, raise_error, monkeypatch): + error = ValueError("processing failed") + + def handler(request): + return httpx.Response(200, json={"items": []}) + + # Inject a transport so requests and cleanup can be tested without network access. + transport = httpx.MockTransport(handler) + if use_async: + http_client = httpx.AsyncClient(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.AsyncClient", lambda **kwargs: http_client) + + async def run(): + client = AsyncSumup(api_key="test") + try: + async with client as entered: + assert entered is client + assert not http_client.is_closed + page = await client.transactions.list("merchant-123") + assert page.items == [] + if raise_error: + raise error + except ValueError as caught: + assert raise_error + assert caught is error + else: + assert not raise_error + assert http_client.is_closed + + asyncio.run(run()) + else: + http_client = httpx.Client(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.Client", lambda **kwargs: http_client) + client = Sumup(api_key="test") + try: + with client as entered: + assert entered is client + assert not http_client.is_closed + page = client.transactions.list("merchant-123") + assert page.items == [] + if raise_error: + raise error + except ValueError as caught: + assert raise_error + assert caught is error + else: + assert not raise_error + assert http_client.is_closed From 369282c3d878ed81885e5f645d50bb35b3f71a8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Tue, 20 Oct 2026 18:22:57 +0200 Subject: [PATCH 2/3] fix: clarify client lifecycle and verify transport cleanup --- README.md | 9 +++++++-- examples/events-fastapi/main.py | 6 ++++-- examples/events-flask/main.py | 2 +- tests/test_client_lifecycle.py | 32 +++++++++++++++++++++++++++----- 4 files changed, 39 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e014848e..42e606cb 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,13 @@ asyncio.run(main()) ``` Context managers close the client when the block exits, including when an exception occurs. -For long-running applications, reuse a client and call `client.close()` or -`await client.aclose()` during shutdown. +For long-running applications, reuse a client across requests to benefit from connection +pooling. During shutdown, wait for outstanding requests and event handlers to finish, then +call `client.close()` or `await client.aclose()`. + +Closing a client is permanent: it cannot send more requests or be reopened. Resources and +event handlers created from that client share its connections, so keep the client open +while they are in use. Create a new client if you need to make requests after closing it. ### Creating a Checkout diff --git a/examples/events-fastapi/main.py b/examples/events-fastapi/main.py index fa23f1bf..489cff70 100644 --- a/examples/events-fastapi/main.py +++ b/examples/events-fastapi/main.py @@ -27,8 +27,10 @@ @asynccontextmanager async def lifespan(_app: FastAPI): - yield - await client._client.aclose() + try: + yield + finally: + await client.aclose() app = FastAPI(lifespan=lifespan) diff --git a/examples/events-flask/main.py b/examples/events-flask/main.py index e854183f..f3eda144 100644 --- a/examples/events-flask/main.py +++ b/examples/events-flask/main.py @@ -52,4 +52,4 @@ def receive_event(): try: app.run(port=8080) finally: - client._client.close() + client.close() diff --git a/tests/test_client_lifecycle.py b/tests/test_client_lifecycle.py index b3b0dbad..b3a05a44 100644 --- a/tests/test_client_lifecycle.py +++ b/tests/test_client_lifecycle.py @@ -6,9 +6,24 @@ from sumup import AsyncSumup, Sumup +class TrackingTransport(httpx.MockTransport): + def __init__(self): + super().__init__(lambda request: httpx.Response(200, json={"items": []})) + self.close_calls = 0 + + def close(self): + self.close_calls += 1 + + async def aclose(self): + self.close_calls += 1 + + @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) -def test_explicit_close(use_async): +def test_explicit_close(use_async, monkeypatch): + transport = TrackingTransport() if use_async: + http_client = httpx.AsyncClient(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.AsyncClient", lambda **kwargs: http_client) async def run(): client = AsyncSumup(api_key="test") @@ -18,22 +33,23 @@ async def run(): asyncio.run(run()) else: + http_client = httpx.Client(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.Client", lambda **kwargs: http_client) client = Sumup(api_key="test") client.close() client.close() assert client._client.is_closed + assert transport.close_calls == 1 + @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("raise_error", [False, True], ids=["success", "exception"]) def test_context_manager_closes_transport(use_async, raise_error, monkeypatch): error = ValueError("processing failed") - def handler(request): - return httpx.Response(200, json={"items": []}) - # Inject a transport so requests and cleanup can be tested without network access. - transport = httpx.MockTransport(handler) + transport = TrackingTransport() if use_async: http_client = httpx.AsyncClient(base_url="https://api.sumup.test", transport=transport) monkeypatch.setattr("sumup._client.httpx.AsyncClient", lambda **kwargs: http_client) @@ -54,6 +70,8 @@ async def run(): else: assert not raise_error assert http_client.is_closed + with pytest.raises(RuntimeError, match="closed"): + await client.transactions.list("merchant-123") asyncio.run(run()) else: @@ -74,3 +92,7 @@ async def run(): else: assert not raise_error assert http_client.is_closed + with pytest.raises(RuntimeError, match="closed"): + client.transactions.list("merchant-123") + + assert transport.close_calls == 1 From 6da54f9b6cd0a37927a893e82e8435e80b582f9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Tue, 20 Oct 2026 18:27:24 +0200 Subject: [PATCH 3/3] docs: show both client usage options --- README.md | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 42e606cb..5e7ef22a 100644 --- a/README.md +++ b/README.md @@ -33,9 +33,9 @@ import os from sumup import Sumup -with Sumup(api_key="sup_sk_MvxmLOl0...") as client: - merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) - print(f"Merchant: {merchant.merchant_code}") +client = Sumup(api_key="sup_sk_MvxmLOl0...") +merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) +print(f"Merchant: {merchant.merchant_code}") ``` ### Async Client @@ -48,22 +48,35 @@ from sumup import AsyncSumup async def main(): - async with AsyncSumup(api_key="sup_sk_MvxmLOl0...") as client: - merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) - print(f"Merchant: {merchant.merchant_code}") + client = AsyncSumup(api_key="sup_sk_MvxmLOl0...") + merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) + print(f"Merchant: {merchant.merchant_code}") asyncio.run(main()) ``` -Context managers close the client when the block exits, including when an exception occurs. -For long-running applications, reuse a client across requests to benefit from connection -pooling. During shutdown, wait for outstanding requests and event handlers to finish, then -call `client.close()` or `await client.aclose()`. +### Client Cleanup + +Use clients directly as shown above, or use a context manager to close connections +automatically when the block exits: + +```python +with Sumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) +``` + +For async code, use `async with`: + +```python +async def main(): + async with AsyncSumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) +``` -Closing a client is permanent: it cannot send more requests or be reopened. Resources and -event handlers created from that client share its connections, so keep the client open -while they are in use. Create a new client if you need to make requests after closing it. +For long-running applications, reuse a client across requests and call `client.close()` +or `await client.aclose()` during shutdown, after outstanding work finishes. +A closed client cannot be reused. ### Creating a Checkout