Restore request context after failures
Request-local state must not become process-global state. ContextVar values follow an asynchronous context, while a module global is shared by unrelated requests. Setting a ContextVar returns a token that can restore the previous binding, including the absence of a previous value.
Nested scopes make this distinction visible: an inner request identifier must disappear when the inner call returns or raises. Resetting to a guessed default would erase an outer binding. The exercise accepts the variable explicitly, so its ownership and restoration can be tested without depending on logging infrastructure.
from contextvars import ContextVar
request=ContextVar("request",default="none")
token=request.set("outer")
print(request.get())
request.reset(token)
print(request.get())Review the design
Context tokens preserve nesting and the original binding. They are scoped to their context; passing a token to a different context is an error rather than a portable way to transfer request state.
Your task
Implement within_context(variable,value,call) returning call() with the temporary binding. Restore the exact previous context even if call raises.
The explanation opens here once every check passes.