feat: add explicit __enter__ and __aenter__ to BaseClient#662
Open
Ghraven wants to merge 1 commit intoollama:mainfrom
Open
feat: add explicit __enter__ and __aenter__ to BaseClient#662Ghraven wants to merge 1 commit intoollama:mainfrom
Ghraven wants to merge 1 commit intoollama:mainfrom
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #642
Problem
async with AsyncClient() as c:raisesTypeErrorat runtime:BaseClientinheritsAbstractContextManagerandAbstractAsyncContextManagerbut only defined__exit__and__aexit__.AbstractContextManagerprovides a default__enter__returningself, butAbstractAsyncContextManager.__aenter__is abstract and raisesTypeErrorif not implemented.Fix
Add explicit
__enter__and__aenter__methods toBaseClient, both returningself, completing the context manager protocol for both sync and async clients.Usage after this change
Notes
__exit__/__aexit__— they still callclose()/await close()as before.Client.__enter__returnsBaseClient— callers using the context manager with type annotations may want to cast toClient/AsyncClientif needed. A follow-up could tighten the return type using generics.