Implements thread-local stack using ContextVar (PEP 567).

This is a reimplementation of the local stack as used by Flask, Werkzeug, Celery, and other libraries to keep a thread-local stack of objects.

  • Supports typing:

    request_stack: LocalStack[Request] = LocalStack()
class mode.utils.locals.LocalStack


Manage state per coroutine (also thread safe).

Most famously used probably in Flask to keep track of the current request object.

push(obj: T) → Generator[[None, None], None]

Push a new item to the stack.

push_without_automatic_cleanup(obj: T) → None
pop() → Optional[T]

Remove the topmost item from the stack.


Will return the old value or None if the stack was already empty.

property stack
property top

Return the topmost item on the stack.

Does not remove it from the stack.


If the stack is empty, None is returned.