From ac1eaec2275daf22accc66b683e99842e49b42ab Mon Sep 17 00:00:00 2001 From: Brandt Bucher Date: Sat, 8 Nov 2025 22:11:02 -0800 Subject: [PATCH] Use for instead of next in contextlib.contextmanager --- Lib/contextlib.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Lib/contextlib.py b/Lib/contextlib.py index 5b646fabca0225..4cda8f2fe4c36f 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -137,22 +137,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