Skip to content

Commit 0608df6

Browse files
committed
gh-151903: Use for loops instead of next() in contextlib
1 parent c698243 commit 0608df6

1 file changed

Lines changed: 10 additions & 18 deletions

File tree

Lib/contextlib.py

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -199,22 +199,18 @@ 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+
for value in self.gen:
203+
return value
204+
raise RuntimeError("generator didn't yield")
206205

207206
def __exit__(self, typ, value, traceback):
208207
if typ is None:
209-
try:
210-
next(self.gen)
211-
except StopIteration:
212-
return False
213-
else:
208+
for _ in self.gen:
214209
try:
215210
raise RuntimeError("generator didn't stop")
216211
finally:
217212
self.gen.close()
213+
return False
218214
else:
219215
if value is None:
220216
# Need to force instantiation so we can reliably
@@ -272,22 +268,18 @@ async def __aenter__(self):
272268
# do not keep args and kwds alive unnecessarily
273269
# they are only needed for recreation, which is not possible anymore
274270
del self.args, self.kwds, self.func
275-
try:
276-
return await anext(self.gen)
277-
except StopAsyncIteration:
278-
raise RuntimeError("generator didn't yield") from None
271+
async for value in self.gen:
272+
return value
273+
raise RuntimeError("generator didn't yield")
279274

280275
async def __aexit__(self, typ, value, traceback):
281276
if typ is None:
282-
try:
283-
await anext(self.gen)
284-
except StopAsyncIteration:
285-
return False
286-
else:
277+
async for _ in self.gen:
287278
try:
288279
raise RuntimeError("generator didn't stop")
289280
finally:
290281
await self.gen.aclose()
282+
return False
291283
else:
292284
if value is None:
293285
# Need to force instantiation so we can reliably

0 commit comments

Comments
 (0)