GH-151903: Use `for` instead of `next` in `contextlib.contextmanager` (GH-141275)

encukou <[email protected]> Mon, 10 Aug 2026 09:39:16 -0400 (EDT)
Newsgroups gmane.comp.python.cvs
Message-ID <[email protected]>
https://github.com/python/cpython/commit/af2e760104cb9d4d518c1360d1165f3acf36159d
commit: af2e760104cb9d4d518c1360d1165f3acf36159d
branch: main
author: Brandt Bucher <[email protected]>
committer: encukou <[email protected]>
date: 2026-08-10T15:39:03+02:00
summary:

GH-151903: Use `for` instead of `next` in `contextlib.contextmanager` (GH-141275)

files:
M Lib/contextlib.py

diff --git a/Lib/contextlib.py b/Lib/contextlib.py
index efc02bfa9243da..f1b958b551af15 100644
--- a/Lib/contextlib.py
+++ b/Lib/contextlib.py
@@ -199,22 +199,20 @@ 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
+        # Slightly faster way to return next(self.gen):
+        for once in self.gen:
+            return once
+        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:
+            # Faster way to run next(self.gen) and check for StopIteration:
+            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

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]