From 0608df667ea7852534dc030a547cee447e8f8443 Mon Sep 17 00:00:00 2001 From: tmvalijib24 Date: Wed, 1 Jul 2026 22:02:22 +0530 Subject: [PATCH 1/2] gh-151903: Use for loops instead of next() in contextlib --- Lib/contextlib.py | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/Lib/contextlib.py b/Lib/contextlib.py index efc02bfa9243da6..ba648416f848493 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -199,22 +199,18 @@ 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: - return next(self.gen) - except StopIteration: - raise RuntimeError("generator didn't yield") from None + for value in self.gen: + return value + raise RuntimeError("generator didn't yield") def __exit__(self, typ, value, traceback): if typ is None: - try: - next(self.gen) - except StopIteration: - return False - else: + for _ in self.gen: try: raise RuntimeError("generator didn't stop") finally: self.gen.close() + return False else: if value is None: # Need to force instantiation so we can reliably @@ -272,22 +268,18 @@ 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: - return await anext(self.gen) - except StopAsyncIteration: - raise RuntimeError("generator didn't yield") from None + async for value in self.gen: + return value + raise RuntimeError("generator didn't yield") async def __aexit__(self, typ, value, traceback): if typ is None: - try: - await anext(self.gen) - except StopAsyncIteration: - return False - else: + async for _ in self.gen: try: raise RuntimeError("generator didn't stop") finally: await self.gen.aclose() + return False else: if value is None: # Need to force instantiation so we can reliably From e4f2608ef5c1f3ea253236bfd02e4e2d0825aed5 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Wed, 1 Jul 2026 16:39:55 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2026-07-01-16-39-54.gh-issue-151903.1Jm-Oc.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2026-07-01-16-39-54.gh-issue-151903.1Jm-Oc.rst diff --git a/Misc/NEWS.d/next/Library/2026-07-01-16-39-54.gh-issue-151903.1Jm-Oc.rst b/Misc/NEWS.d/next/Library/2026-07-01-16-39-54.gh-issue-151903.1Jm-Oc.rst new file mode 100644 index 000000000000000..3a09e4eb653f28e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-01-16-39-54.gh-issue-151903.1Jm-Oc.rst @@ -0,0 +1 @@ +Optimize ``contextlib.contextmanager`` and ``contextlib.asynccontextmanager`` by replacing explicit ``next()`` and ``anext()`` calls with ``for`` and ``async for`` loops.