Generator Handoff: One Yield Between Entry and Exit
2026-11-21

Generator Handoff: One Yield Between Entry and Exit

Generator Handoff divides a context manager into setup, the caller's managed body and the generator's exit processing. The contextlib.contextmanager decorator adapts a generator function to this protocol. Its single yield hands a value to the with statement and pauses the generator while the managed body runs. Exit then resumes the generator, either normally or with the body's exception.

One yielded value connects entry to the managed body

The Python contextlib reference requires the decorated generator to yield exactly one value. That value becomes the target of the with statement's as clause. In an original local example, the generator appends enter to an event list, enters a try block and yields the string token. The managed body records that received value.

On normal completion, the generator continues after yield and appends after_yield. Its finally clause then appends cleanup. The complete local record is enter, body:token, after_yield, cleanup. Those events show two distinct execution contexts taking turns: the generator runs before the body, pauses for it and later resumes to finish.

The yielded value is an ordinary object supplied by the generator. It is not automatically a file, an acquired resource or a result proving that setup validated an application. The example intentionally yields a small string so the handoff can be examined without opening a resource or attributing a cleanup action to a real equipment operation.

Generatorenter/yield pausesforbodytoken, normalresumeafter_yieldthenfinallycleanup.
Original local event trace, no resource acquisition claim. Source: Zhilianhai editorial desk, original AI-assisted conceptual illustration.

An exception in the body is raised at the yield boundary

For a second local run, the managed body records body:token and raises an illustrative ValueError. The generator catches ValueError around its yield, records caught, re-raises it and executes the finally clause. The surrounding caller then records propagated. This run produces enter, body:token, caught, cleanup, propagated.

Notice that after_yield is absent from this second record. The exception does not act like a normal continuation through the next statement. It is raised at the suspended yield point and follows the generator's applicable exception path. Cleanup appears because the example explicitly places it in finally around that boundary.

This does not mean that any arbitrary generator code automatically provides correct cleanup for every possible setup failure. Placement matters. A finally clause only governs the code within its defined control-flow scope. The example and diagrams concern the stated body exception after the generator has successfully reached its single yield.

BodyValueErrorthrownatyield, caughtthenreraised,after_yieldskipped,cleanupandcallerpropagation.
Cleanup placement is explicit; not a retry or rollback. Source: Zhilianhai editorial desk, original AI-assisted conceptual illustration.

Logging an exception is different from suppressing it

The reference says that a generator catching an exception only to log or perform another action must re-raise it if propagation is intended. Otherwise, normal termination of the generator can indicate that the exception has been handled. In the local example, the explicit re-raise is why the surrounding caller still receives ValueError after cleanup.

The versioned implementation reflects this distinction in its exit method. Normal exit advances the generator toward completion. Exceptional exit throws the exception into it and interprets how it terminates or raises. These branches adapt generator behavior to the context-manager exit protocol; they do not retry the failed statement in the managed body.

The generator must stop rather than yield a second value

A local deliberately invalid example yielded once for entry and then yielded a second value during exit. The adapter raised RuntimeError with the message generator didn't stop. A second yield is not another opportunity to execute the same with body. This interface uses one handoff boundary, rather than an ordinary loop that consumes an arbitrary stream of values.

A generator that stops without yielding cannot provide the required entry value either. The implementation converts that condition into a corresponding runtime error. Reading the one-yield requirement alongside both entry and exit checks makes the protocol clearer than describing the decorator as merely allowing any generator to appear in a with statement.

The factory can be called again to create another context-manager instance. An already used generator-backed instance, however, is a one-shot object. It has progressed through its own generator state. The base implementation provides a recreation path for decorator use, creating a fresh instance rather than rewinding a previously exhausted generator.

Review setup, handoff and exit as separate stages

A useful review traces the yielded value, normal continuation, exceptional continuation and cleanup placement. Record whether a caught exception is re-raised. These details explain both the event order and the caller-visible outcome. The mere presence of finally in a code listing should not be substituted for reading which statements its scope actually covers.

The technical learning collection and equipment software notes provide related interface context. All events here came from small local teaching generators. The original figures show control handoff and propagation, without claiming that a real resource was acquired, that earlier work was rolled back or that every context-manager class shares this generator-specific single-use behavior.

18028484626 CONTACT US

公司:智联海(惠州)科技有限公司

地址:惠州仲恺高新区陈江街道白云山工业大道 5 号六楼 601

Q Q:18028484626

Copyright © 2002-2026

粤xxx

咨询 在线留言 电话:18028484626
微信 微信扫码添加我