-
Notifications
You must be signed in to change notification settings - Fork 150
Added context manager mix-in classes #905
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
dc683b0
Added context manager mix-in classes
agronholm 5997105
Updated the documentation
agronholm 664a19f
Merge branch 'master' into contextmanagermixin
agronholm 3765c28
Fixed updated documentation section
agronholm 7aaec76
Made the type variable covariant
agronholm 84685d9
Addressed reentrancy by raising RuntimeError if attempting to enter a…
agronholm a8fbf36
Merge branch 'master' into contextmanagermixin
agronholm 68884e3
Merge branch 'master' into contextmanagermixin
agronholm 5254a11
Merge branch 'master' into contextmanagermixin
agronholm 915b172
Merge branch 'master' into contextmanagermixin
agronholm 7f5c4b5
Delete self.__cm instead of setting to None
agronholm 921c880
Enforced context manager decorators on the dunder methods
agronholm b71f419
Fix contextmanager mixin typing (#912)
tapetersen dcba443
Merge branch 'master' into contextmanagermixin
agronholm 562d21a
Added documentation section for context manager mix-ins
agronholm 09a5a9e
Added documentation cross-references to the API docs
agronholm 7334290
Added attribution
agronholm b3c38db
Merge branch 'master' into contextmanagermixin
agronholm b67e36c
Merge branch 'master' into contextmanagermixin
agronholm 492120a
Improved the documentation
agronholm 55a941a
Merge branch 'master' into contextmanagermixin
agronholm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
from __future__ import annotations | ||
|
||
from abc import abstractmethod | ||
from collections.abc import AsyncGenerator, Generator | ||
from inspect import isasyncgen, iscoroutine | ||
from types import TracebackType | ||
from typing import Generic, TypeVar, final | ||
|
||
_T_co = TypeVar("_T_co", covariant=True) | ||
|
||
|
||
class ContextManagerMixin(Generic[_T_co]): | ||
""" | ||
Mixin class providing context manager functionality via a generator-based | ||
implementation. | ||
|
||
This class allows you to implement a context manager via :meth:`__contextmanager__` | ||
which should return a generator. The mechanics are meant to mirror those of | ||
:func:`@contextmanager <contextlib.contextmanager>`. | ||
""" | ||
|
||
@final | ||
def __enter__(self) -> _T_co: | ||
gen = self.__contextmanager__() | ||
if not isinstance(gen, Generator): | ||
raise TypeError( | ||
f"__contextmanager__() did not return a generator object, " | ||
f"but {gen.__class__!r}" | ||
) | ||
|
||
try: | ||
value = gen.send(None) | ||
except StopIteration: | ||
raise RuntimeError( | ||
"the __contextmanager__() generator returned without yielding a value" | ||
) from None | ||
|
||
self.__cm = gen | ||
return value | ||
|
||
@final | ||
def __exit__( | ||
self, | ||
exc_type: type[BaseException] | None, | ||
exc_val: BaseException | None, | ||
exc_tb: TracebackType | None, | ||
) -> bool | None: | ||
# Prevent circular references | ||
cm = self.__cm | ||
del self.__cm | ||
|
||
if exc_val is not None: | ||
try: | ||
cm.throw(exc_val) | ||
except StopIteration: | ||
return True | ||
else: | ||
try: | ||
cm.send(None) | ||
except StopIteration: | ||
return None | ||
|
||
cm.close() | ||
raise RuntimeError("the __contextmanager__() generator didn't stop") | ||
|
||
@abstractmethod | ||
def __contextmanager__(self) -> Generator[_T_co, None, None]: | ||
""" | ||
Implement your context manager logic here, as you would with | ||
:func:`@contextmanager <contextlib.contextmanager>`. | ||
|
||
Any code up to the ``yield`` will be run in ``__enter__()``, and any code after | ||
it is run in ``__exit__()``. | ||
|
||
.. note:: If an exception is raised in the context block, it is reraised from | ||
the ``yield``, just like with | ||
:func:`@contextmanager <contextlib.contextmanager>`. | ||
|
||
:return: a generator that yields exactly once | ||
""" | ||
|
||
|
||
class AsyncContextManagerMixin(Generic[_T_co]): | ||
""" | ||
Mixin class providing async context manager functionality via a generator-based | ||
implementation. | ||
|
||
This class allows you to implement a context manager via | ||
:meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of | ||
:func:`@asynccontextmanager <contextlib.asynccontextmanager>`. | ||
""" | ||
|
||
@final | ||
async def __aenter__(self) -> _T_co: | ||
gen = self.__asynccontextmanager__() | ||
if not isasyncgen(gen): | ||
if iscoroutine(gen): | ||
gen.close() | ||
raise TypeError( | ||
"__asynccontextmanager__() returned a coroutine object instead of " | ||
"an async generator. Did you forget to add 'yield'?" | ||
) | ||
|
||
raise TypeError( | ||
f"__asynccontextmanager__() did not return an async generator object, " | ||
f"but {gen.__class__!r}" | ||
) | ||
|
||
try: | ||
value = await gen.asend(None) | ||
except StopAsyncIteration: | ||
raise RuntimeError( | ||
"the __asynccontextmanager__() generator returned without yielding a " | ||
"value" | ||
) from None | ||
|
||
self.__cm = gen | ||
return value | ||
|
||
@final | ||
async def __aexit__( | ||
self, | ||
exc_type: type[BaseException] | None, | ||
exc_val: BaseException | None, | ||
exc_tb: TracebackType | None, | ||
) -> bool | None: | ||
# Prevent circular references | ||
cm = self.__cm | ||
del self.__cm | ||
|
||
if exc_val is not None: | ||
try: | ||
await cm.athrow(exc_val) | ||
except StopAsyncIteration: | ||
return True | ||
else: | ||
try: | ||
await cm.asend(None) | ||
except StopAsyncIteration: | ||
return None | ||
|
||
await cm.aclose() | ||
raise RuntimeError("the __asynccontextmanager__() generator didn't stop") | ||
|
||
@abstractmethod | ||
def __asynccontextmanager__(self) -> AsyncGenerator[_T_co, None]: | ||
""" | ||
Implement your async context manager logic here, as you would with | ||
:func:`@asynccontextmanager <contextlib.asynccontextmanager>`. | ||
|
||
Any code up to the ``yield`` will be run in ``__aenter__()``, and any code after | ||
it is run in ``__aexit__()``. | ||
|
||
.. note:: If an exception is raised in the context block, it is reraised from | ||
the ``yield``, just like with | ||
:func:`@asynccontextmanager <contextlib.asynccontextmanager>`. | ||
|
||
:return: an async generator that yields exactly once | ||
""" |
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh this was slightly wrong it should have used pop_all()
I think it's worth including an (Async)ExitStack instruction on how to do this