From 2b4d25d26f3b4f53f1e92903f3a96b47a8e350eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=20=C3=96mer=20Yasan?= <105012194+aliysnm@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:01:25 +0000 Subject: [PATCH 1/2] gh-163064: Raise RuntimeError when reusing a contextmanager Since gh-74492, _GeneratorContextManager.__enter__ and _AsyncGeneratorContextManager.__aenter__ start by deleting self.args, self.kwds and self.func. Entering the same context manager a second time therefore failed with an AttributeError about an internal attribute instead of the documented RuntimeError("generator didn't yield"). Raise that RuntimeError when the attributes are already gone, without touching the generator, so that re-entering an active context manager also doesn't advance the suspended generator. --- Lib/contextlib.py | 12 +++++-- Lib/test/test_contextlib.py | 30 +++++++++++++++++ Lib/test/test_contextlib_async.py | 32 +++++++++++++++++++ ...2-03-09-01-20.gh-issue-163064.2QwY0oaB.rst | 4 +++ 4 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-12-03-09-01-20.gh-issue-163064.2QwY0oaB.rst diff --git a/Lib/contextlib.py b/Lib/contextlib.py index f1b958b551af15..f1502e778be6ea 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -198,7 +198,11 @@ class _GeneratorContextManager( def __enter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore - del self.args, self.kwds, self.func + try: + del self.args, self.kwds, self.func + except AttributeError: + # Already entered once: don't touch the generator again. + raise RuntimeError("generator didn't yield") from None # Slightly faster way to return next(self.gen): for once in self.gen: return once @@ -269,7 +273,11 @@ class _AsyncGeneratorContextManager( async def __aenter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore - del self.args, self.kwds, self.func + try: + del self.args, self.kwds, self.func + except AttributeError: + # Already entered once: don't touch the generator again. + raise RuntimeError("generator didn't yield") from None try: return await anext(self.gen) except StopAsyncIteration: diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index e291f814edbd93..ba0b62866fc913 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -182,6 +182,36 @@ def whoo(): with self.assertRaises(RuntimeError): ctx.__enter__() + def test_contextmanager_reuse(self): + state = [] + @contextmanager + def woohoo(): + state.append('enter') + yield + state.append('exit') + ctx = woohoo() + with ctx: + pass + with self.assertRaisesRegex(RuntimeError, "generator didn't yield"): + with ctx: + pass + self.assertEqual(state, ['enter', 'exit']) + + def test_contextmanager_reenter_while_active(self): + state = [] + @contextmanager + def woohoo(): + state.append('enter') + yield + state.append('exit') + ctx = woohoo() + with ctx: + with self.assertRaisesRegex(RuntimeError, "generator didn't yield"): + ctx.__enter__() + # The suspended generator must not have been advanced. + self.assertEqual(state, ['enter']) + self.assertEqual(state, ['enter', 'exit']) + def test_contextmanager_trap_second_yield(self): @contextmanager def whoo(): diff --git a/Lib/test/test_contextlib_async.py b/Lib/test/test_contextlib_async.py index 95bdfdb3d9d4a6..863560a4199ae1 100644 --- a/Lib/test/test_contextlib_async.py +++ b/Lib/test/test_contextlib_async.py @@ -222,6 +222,38 @@ async def whoo(): with self.assertRaises(RuntimeError): await ctx.__aenter__() + @_async_test + async def test_contextmanager_reuse(self): + state = [] + @asynccontextmanager + async def woohoo(): + state.append('enter') + yield + state.append('exit') + ctx = woohoo() + async with ctx: + pass + with self.assertRaisesRegex(RuntimeError, "generator didn't yield"): + async with ctx: + pass + self.assertEqual(state, ['enter', 'exit']) + + @_async_test + async def test_contextmanager_reenter_while_active(self): + state = [] + @asynccontextmanager + async def woohoo(): + state.append('enter') + yield + state.append('exit') + ctx = woohoo() + async with ctx: + with self.assertRaisesRegex(RuntimeError, "generator didn't yield"): + await ctx.__aenter__() + # The suspended generator must not have been advanced. + self.assertEqual(state, ['enter']) + self.assertEqual(state, ['enter', 'exit']) + @_async_test async def test_contextmanager_trap_second_yield(self): @asynccontextmanager diff --git a/Misc/NEWS.d/next/Library/2026-12-03-09-01-20.gh-issue-163064.2QwY0oaB.rst b/Misc/NEWS.d/next/Library/2026-12-03-09-01-20.gh-issue-163064.2QwY0oaB.rst new file mode 100644 index 00000000000000..ec394a0f39d180 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-03-09-01-20.gh-issue-163064.2QwY0oaB.rst @@ -0,0 +1,4 @@ +Reusing a single-use context manager created by +:func:`contextlib.contextmanager` or :func:`contextlib.asynccontextmanager` +now raises the documented :exc:`RuntimeError` instead of an +:exc:`AttributeError`. From 7c159f3a277657a92523feaec3f3b4d9f714bcfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=20=C3=96mer=20Yasan?= <105012194+aliysnm@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:20:55 +0000 Subject: [PATCH 2/2] Test that an AttributeError from the generator is not swallowed --- Lib/test/test_contextlib.py | 13 +++++++++++++ Lib/test/test_contextlib_async.py | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index ba0b62866fc913..e83ecc34d463f7 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -212,6 +212,19 @@ def woohoo(): self.assertEqual(state, ['enter']) self.assertEqual(state, ['enter', 'exit']) + def test_contextmanager_preserves_generator_attributeerror(self): + # Only the attribute deletion is guarded: an AttributeError raised + # by the generator itself must propagate unchanged. + exc = AttributeError('generator failure') + @contextmanager + def woohoo(): + raise exc + yield + with self.assertRaises(AttributeError) as cm: + with woohoo(): + pass + self.assertIs(cm.exception, exc) + def test_contextmanager_trap_second_yield(self): @contextmanager def whoo(): diff --git a/Lib/test/test_contextlib_async.py b/Lib/test/test_contextlib_async.py index 863560a4199ae1..3c7d0b13eaacc7 100644 --- a/Lib/test/test_contextlib_async.py +++ b/Lib/test/test_contextlib_async.py @@ -254,6 +254,20 @@ async def woohoo(): self.assertEqual(state, ['enter']) self.assertEqual(state, ['enter', 'exit']) + @_async_test + async def test_contextmanager_preserves_generator_attributeerror(self): + # Only the attribute deletion is guarded: an AttributeError raised + # by the generator itself must propagate unchanged. + exc = AttributeError('generator failure') + @asynccontextmanager + async def woohoo(): + raise exc + yield + with self.assertRaises(AttributeError) as cm: + async with woohoo(): + pass + self.assertIs(cm.exception, exc) + @_async_test async def test_contextmanager_trap_second_yield(self): @asynccontextmanager