Repository navigation
Conversation
Since pythongh-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.
98a5dd5 to
2b4d25d
Compare
|
A complementary compatibility guard for the new sentinel = AttributeError('user generator failure')
@contextmanager
def cm():
raise sentinel
yield
with self.assertRaises(AttributeError) as caught:
with cm():
pass
self.assertIs(caught.exception, sentinel)I ran entry-before-yield and cleanup-after-yield variants for both contextmanager and asynccontextmanager on CPython 3.12.16/Linux: all four preserve the sentinel. I then substituted only the exact The current try block is correctly restricted to deleting the recreation attributes. Explicit user-AttributeError identity coverage would protect that boundary against accidentally widening it to generator advancement later. I checked the new sync/async reuse tests and the existing AttributeError mentions in both test modules; those mentions concern abstract managers/ExitStack rather than this generator-entry boundary. AI-assisted investigation; no full-main or patch-suite passing claim. |
|
Thanks for checking this and for running the variants. Agreed, that boundary is worth pinning down. I've added sync and async tests asserting that an |
Fixes gh-163064.
Since gh-74492 (3.7),
_GeneratorContextManager.__enter__and_AsyncGeneratorContextManager.__aenter__start withdel self.args, self.kwds, self.func. Entering the same context manager a second time therefore fails withAttributeError: '_GeneratorContextManager' object has no attribute 'args', not with theRuntimeError: generator didn't yieldthat the contextlib docs show.This PR raises that
RuntimeErrorwhen the attributes are already gone. It deliberately does not touch the generator, so re-entering a context manager that is still active doesn't advance the suspended generator, which would run its cleanup code too early.Tests:
test_contextmanager_reuse: a secondwithraisesRuntimeError.test_contextmanager_reenter_while_active: re-entering inside the active block raisesRuntimeErrorand leaves the generator suspended.Both are added for the sync and async variants. All four fail on
mainwithout the change, andtest_contextlibandtest_contextlib_asyncpass with it.I found this by running the examples in the docs' literal blocks against a fresh build. I used an AI assistant to find the bug and to write the patch. The tests above were run locally on a debug build of
main.