Skip to content

gh-151903: Optimize context managers by replacing next() with for loops#152806

Closed
tmvalijib24 wants to merge 4 commits into
python:mainfrom
tmvalijib24:gh-151903-optimize-contextmanager
Closed

gh-151903: Optimize context managers by replacing next() with for loops#152806
tmvalijib24 wants to merge 4 commits into
python:mainfrom
tmvalijib24:gh-151903-optimize-contextmanager

Conversation

@tmvalijib24

@tmvalijib24 tmvalijib24 commented Jul 1, 2026

Copy link
Copy Markdown

Fixes #151903

Description

This PR optimizes context managers by replacing explicit next() and anext() iteration calls with structured for and async for loops within _GeneratorContextManager and _AsyncGeneratorContextManager inside Lib/contextlib.py.

Why this helps:

  • Avoids the overhead of creating, raising, and catching StopIteration or StopAsyncIteration exceptions on successful context blocks.
  • Allows the interpreter to leverage bytecode specialization for generator iteration.

Tests

  • Ran and verified locally via ./python -m test test_contextlib (all tests passed successfully).

@bedevere-app

bedevere-app Bot commented Jul 1, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@python-cla-bot

python-cla-bot Bot commented Jul 1, 2026

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@StanFromIreland

StanFromIreland commented Jul 1, 2026

Copy link
Copy Markdown
Member

The issue already has an open PR (by Brandt himself), closing in favour of the existing work.

@tmvalijib24

Copy link
Copy Markdown
Author

Hi @StanFromIreland, I am New to Open Source and interested in Contributing for Cpython, is there any discord channel in which I can connect to the maintainers and contributors?

@tmvalijib24 tmvalijib24 deleted the gh-151903-optimize-contextmanager branch July 2, 2026 05:58
@StanFromIreland

Copy link
Copy Markdown
Member

I'm afraid there isn't, I suggest reading the devguide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize contextlib.contextmanager to use for loops instead of next

2 participants