You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
contextmanager: reusing a single-use context manager raises AttributeError instead of the documented RuntimeError #163064
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:
But the second use actually raises an AttributeError that refers to an internal attribute:
fromcontextlibimportcontextmanager@contextmanagerdefsingleuse():
yieldcm=singleuse()
withcm:
passwithcm: # 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.
Activity
pythongh-163064: Raise RuntimeError when reusing a contextmanager