Skip to content

feat: add explicit __enter__ and __aenter__ to BaseClient#662

Open
Ghraven wants to merge 1 commit intoollama:mainfrom
Ghraven:feat/context-manager-enter-methods
Open

feat: add explicit __enter__ and __aenter__ to BaseClient#662
Ghraven wants to merge 1 commit intoollama:mainfrom
Ghraven:feat/context-manager-enter-methods

Conversation

@Ghraven
Copy link
Copy Markdown

@Ghraven Ghraven commented May 3, 2026

Fixes #642

Problem

async with AsyncClient() as c: raises TypeError at runtime:

TypeError: object AsyncClient can't be used in 'async with' statement

BaseClient inherits AbstractContextManager and AbstractAsyncContextManager but only defined __exit__ and __aexit__. AbstractContextManager provides a default __enter__ returning self, but AbstractAsyncContextManager.__aenter__ is abstract and raises TypeError if not implemented.

Fix

Add explicit __enter__ and __aenter__ methods to BaseClient, both returning self, completing the context manager protocol for both sync and async clients.

Usage after this change

# Sync
with Client() as client:
    response = client.chat(...)

# Async
async with AsyncClient() as client:
    response = await client.chat(...)

Notes

  • No behaviour change to __exit__ / __aexit__ — they still call close() / await close() as before.
  • Client.__enter__ returns BaseClient — callers using the context manager with type annotations may want to cast to Client / AsyncClient if needed. A follow-up could tighten the return type using generics.

Fixes ollama#642

While `BaseClient` inherits from both `AbstractContextManager` and
`AbstractAsyncContextManager`, it only defined `__exit__` and `__aexit__`.
`AbstractContextManager` provides a default `__enter__` that returns `self`,
but `AbstractAsyncContextManager.__aenter__` is abstract and must be
implemented explicitly — meaning `async with AsyncClient() as c:` raised
`TypeError` at runtime.

This commit adds explicit `__enter__` and `__aenter__` methods that both
return `self`, completing the context manager protocol for both sync and
async clients and making `with Client() as c:` and `async with AsyncClient() as c:`
work as expected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant