Skip to content

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

Backlog

Description

@aliysnm

Bug report

Bug description:

The contextlib docs (Single use, reusable and reentrant context managers) say that context managers created with @contextmanager "will complain about the underlying generator failing to yield if an attempt is made to use them a second time", and show:

>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield

But the second use actually raises an AttributeError that refers to an internal attribute:

from contextlib import contextmanager

@contextmanager
def singleuse():
    yield

cm = singleuse()
with cm:
    pass
with cm:   # AttributeError: '_GeneratorContextManager' object has no attribute 'args'
    pass

asynccontextmanager behaves the same way ('_AsyncGeneratorContextManager' object has no attribute 'args').

This seems to date from gh-74492 (bpo-30306, 3.7). __enter__/__aenter__ now start with del self.args, self.kwds, self.func, which fails on the second call before the code that raises RuntimeError("generator didn't yield") is reached. I reproduced it on 3.12 and on current main.

I'd suggest raising the documented RuntimeError when those attributes are already gone. Checking this up front, without touching the generator, also keeps a nested re-entry of an active context manager from advancing the suspended generator. I have a patch with tests ready.

CPython versions tested on:

3.12, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Dec 3, 2026
  2. added a commit that references this issue on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions