Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
While investigating
ContextVar
in pallets/werkzeug#2436, I realized that there's no reason to use aLocalStack
now to manageRequestContext
andAppContext
.LocalStack
incurs some performance and memory overhead on everypush
andpop
because it uses a mutable list as the value of theContextVar
. Since we can never know if this context was copied byasyncio
or asgiref into a child context, we always have to copy the list before mutating it, then set it again, otherwise mutations would be unsafe.RequestContext
andAppContext
already have their own internal thread-unsafe state to track how many times they've been pushed, and implicit app contexts for request contexts.Now, the contexts keep an internal stack of
contextvars.Token
objects, appending a new token when pushed. This allows resetting the context var to the previous value when the context is popped. Essentially, this makes the contexts singly-linked lists instead of stacks.This does mean that
_app_ctx_stack.top
and_request_ctx_stack.top
will no longer exist. Currently, there is a fake object that keeps the API around, since it's used by extensions to store state. However, importing them or accessing them will show deprecation warnings. Docs now encourage usingg
instead of the internal contexts for extension state. I addedapp_ctx
andrequest_ctx
objects that are proxies to the current objects, in case existing extensions want a less drastic change.This bumps the minimum version of Werkzeug to 2.2 (currently 2.2.0a1) to take advantage of changes to its implementation of
LocalProxy
.