diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2023-10-10 07:43:04 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-10-10 07:43:04 (GMT) |
commit | 96fed66a65097eac2dc528ce29c9ba676bb07689 (patch) | |
tree | 5df0c034d82f6604b2ac0f0375d5ac556d914a44 /Lib/contextlib.py | |
parent | def7ea5cec41e8d3112641bb4af7572c0ac4f380 (diff) | |
download | cpython-96fed66a65097eac2dc528ce29c9ba676bb07689.zip cpython-96fed66a65097eac2dc528ce29c9ba676bb07689.tar.gz cpython-96fed66a65097eac2dc528ce29c9ba676bb07689.tar.bz2 |
gh-110378: Close invalid generators in contextmanager and asynccontextmanager (GH-110499)
contextmanager and asynccontextmanager context managers now close an invalid
underlying generator object that yields more then one value.
Diffstat (limited to 'Lib/contextlib.py')
-rw-r--r-- | Lib/contextlib.py | 20 |
1 files changed, 16 insertions, 4 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index f82e7bc..6994690 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -149,7 +149,10 @@ class _GeneratorContextManager( except StopIteration: return False else: - raise RuntimeError("generator didn't stop") + try: + raise RuntimeError("generator didn't stop") + finally: + self.gen.close() else: if value is None: # Need to force instantiation so we can reliably @@ -191,7 +194,10 @@ class _GeneratorContextManager( raise exc.__traceback__ = traceback return False - raise RuntimeError("generator didn't stop after throw()") + try: + raise RuntimeError("generator didn't stop after throw()") + finally: + self.gen.close() class _AsyncGeneratorContextManager( _GeneratorContextManagerBase, @@ -216,7 +222,10 @@ class _AsyncGeneratorContextManager( except StopAsyncIteration: return False else: - raise RuntimeError("generator didn't stop") + try: + raise RuntimeError("generator didn't stop") + finally: + await self.gen.aclose() else: if value is None: # Need to force instantiation so we can reliably @@ -258,7 +267,10 @@ class _AsyncGeneratorContextManager( raise exc.__traceback__ = traceback return False - raise RuntimeError("generator didn't stop after athrow()") + try: + raise RuntimeError("generator didn't stop after athrow()") + finally: + await self.gen.aclose() def contextmanager(func): |