Skip to content

Commit af2e760

Browse files
authored
GH-151903: Use for instead of next in contextlib.contextmanager (GH-141275)
1 parent 8a4ee5c commit af2e760

1 file changed

Lines changed: 7 additions & 9 deletions

File tree

Lib/contextlib.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -199,22 +199,20 @@ def __enter__(self):
199199
# do not keep args and kwds alive unnecessarily
200200
# they are only needed for recreation, which is not possible anymore
201201
del self.args, self.kwds, self.func
202-
try:
203-
return next(self.gen)
204-
except StopIteration:
205-
raise RuntimeError("generator didn't yield") from None
202+
# Slightly faster way to return next(self.gen):
203+
for once in self.gen:
204+
return once
205+
raise RuntimeError("generator didn't yield")
206206

207207
def __exit__(self, typ, value, traceback):
208208
if typ is None:
209-
try:
210-
next(self.gen)
211-
except StopIteration:
212-
return False
213-
else:
209+
# Faster way to run next(self.gen) and check for StopIteration:
210+
for _ in self.gen:
214211
try:
215212
raise RuntimeError("generator didn't stop")
216213
finally:
217214
self.gen.close()
215+
return False
218216
else:
219217
if value is None:
220218
# Need to force instantiation so we can reliably

0 commit comments

Comments
 (0)