PythiloLesson 4 of 12 · progress kept in this browser

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())
Your task

Implement within_context(variable,value,call) returning call() with the temporary binding. Restore the exact previous context even if call raises.