Skip to content

Optimize contextlib.contextmanager to use for loops instead of next #151903

@brandtbucher

Description

@brandtbucher

The implementation of contextlib.contextmanager currently advances the wrapped generator using explicit next calls.

Replacing these with equivalent for loops allows the interpreter to take advantage of existing iterator-loop optimizations:

  • Generator iteration in for loops can be specialized more effectively than direct next calls.
  • The interpreter can avoid constructing and raising StopIteration exceptions in the common case where loop termination is expected.
  • This is also more JIT-friendly, since iteration is expressed using a common language construct rather than explicit exception-driven control flow.

Local microbenchmarks of entering and exiting a context manager repeatedly show measurable reductions in the overhead introduced by _GeneratorContextManager.

This issue tracks updating the implementation to use for loops where appropriate.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions