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
ContextVarin pallets/werkzeug#2436, I realized that there's no reason to use aLocalStacknow to manageRequestContextandAppContext.LocalStackincurs some performance and memory overhead on everypushandpopbecause it uses a mutable list as the value of theContextVar. Since we can never know if this context was copied byasyncioor asgiref into a child context, we always have to copy the list before mutating it, then set it again, otherwise mutations would be unsafe.RequestContextandAppContextalready 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.Tokenobjects, 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.topand_request_ctx_stack.topwill 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 usingginstead of the internal contexts for extension state. I addedapp_ctxandrequest_ctxobjects 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.