Debian Codegraph @

src/anthropic/lib/credentials/_close.py

raw
1 from __future__ import annotations
2
3 import inspect
4 from typing import Protocol
5 from typing_extensions import runtime_checkable
6
7 from ._types import unwrap_partial
8
9 __all__ = ["close_credentials", "async_close_credentials", "has_async_close"]
10
11
12 @runtime_checkable
13 class SupportsClose(Protocol):
14 def close(self) -> object: ...
15
16
17 @runtime_checkable
18 class SupportsAsyncClose(Protocol):
19 def aclose(self) -> object: ...
20
21
22 # `credentials` is typed `object` in all three: `close()` / `aclose()` are not part of
23 # the provider protocols, so the checks below are the only thing that knows they are there.
24 # A functools.partial hides the provider's own hooks, so each looks at the object it wraps.
25
26
27 def has_async_close(credentials: object) -> bool:
28 """True if the provider's `close()` is `async def`, which only `AsyncAnthropic` can await."""
29 provider = unwrap_partial(credentials)
30 return isinstance(provider, SupportsClose) and inspect.iscoroutinefunction(provider.close)
31
32
33 def close_credentials(credentials: object) -> None:
34 """Release any resources owned by a credential provider, if it exposes `close()`."""
35 provider = unwrap_partial(credentials)
36 if isinstance(provider, SupportsClose):
37 provider.close()
38
39
40 async def async_close_credentials(credentials: object) -> None:
41 """Async `close_credentials`: awaits the provider's `aclose()` if it has one, else calls `close()`."""
42 provider = unwrap_partial(credentials)
43 if isinstance(provider, SupportsAsyncClose):
44 closing = provider.aclose()
45 elif isinstance(provider, SupportsClose):
46 closing = provider.close()
47 else:
48 return
49 # Awaited only if there is something to await. close() may itself be `async def`, as on
50 # aiohttp-style clients; aclose() may be a plain method, and a `Mock` provider has both hooks
51 # and returns another `Mock` from each. Closing a client should not fail on any of them.
52 if inspect.isawaitable(closing):
53 await closing