Skip to content

gh-163064: Raise RuntimeError when reusing a contextmanager - #163065

Open
aliysnm wants to merge 2 commits into
python:mainfrom
aliysnm:gh-163064-contextmanager-reuse
Open

aliysnm wants to merge 2 commits into
python:mainfrom
aliysnm:gh-163064-contextmanager-reuse

Conversation

@aliysnm

@aliysnm aliysnm commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes gh-163064.

Since gh-74492 (3.7), _GeneratorContextManager.__enter__ and _AsyncGeneratorContextManager.__aenter__ start with del self.args, self.kwds, self.func. Entering the same context manager a second time therefore fails with AttributeError: '_GeneratorContextManager' object has no attribute 'args', not with the RuntimeError: generator didn't yield that the contextlib docs show.

This PR raises that RuntimeError when 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 second with raises RuntimeError.
  • test_contextmanager_reenter_while_active: re-entering inside the active block raises RuntimeError and leaves the generator suspended.

Both are added for the sync and async variants. All four fail on main without the change, and test_contextlib and test_contextlib_async pass 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.

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.
@efanntyo

efanntyo commented Dec 3, 2026

Copy link
Copy Markdown

A complementary compatibility guard for the new except AttributeError would be preserving an AttributeError raised by the user generator, including its object identity. For example, an entry-side sync control is:

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 __enter__ / __aenter__ methods extracted from head 2b4d25d; the same four controls still preserve it. The source was hash checked, but this is method-level substitution on a 3.12 host, not a full PR module/build (the host cannot parse main's lazy-import syntax).

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.

@aliysnm

aliysnm commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

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 AttributeError raised by the generator itself propagates as the same object (7c159f3). I also checked that they fail if the try block is widened to cover advancing the generator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

contextmanager: reusing a single-use context manager raises AttributeError instead of the documented RuntimeError

2 participants