pallets/flask · error · RuntimeError

Cannot pop this context

Error message

Cannot pop this context ({self!r}), it is not pushed.

What it means

RequestContext/AppContext.pop() checks self._cv_token; if it is None the context was never pushed (the token is set during push()). Calling pop() on an un-pushed context raises RuntimeError naming the context. This catches unbalanced pop() calls and context-manager misuse.

Solutions

  1. Use the context as a context manager (with ctx:) so push/pop are balanced automatically.
  2. If pushing manually, ensure every push() has exactly one matching pop() and pop() is never called first.
  3. Track push state yourself or check ctx._cv_token is not None before calling pop().

Example fix

# before
ctx = app.test_request_context()
ctx.pop()  # never pushed -> RuntimeError

# after
ctx = app.test_request_context()
ctx.push()
try:
    ...
finally:
    ctx.pop()
# or simply: with app.test_request_context(): ...
Defensive patterns

Strategy: validation

Validate before calling

def can_pop(ctx) -> bool:
    return getattr(ctx, '_cv_token', None) is not None

Type guard

null

Try / catch

try:
    ctx.pop()
except RuntimeError as e:
    if 'not pushed' in str(e):
        pass  # already popped / never pushed; ignore
    else:
        raise

Prevention

When it happens

Trigger: Manually calling ctx.pop() before ctx.push(), or calling pop() twice after only one push (the second pop sees _cv_token cleared on final pop). Using the context object outside its 'with' block after it has already been popped.

Common situations: Manual context push/pop management with a typo in ordering. Teardown logic that pops unconditionally. A context already exited via 'with' then popped again in a finally clause.

Related errors


AI-assisted analysis of pallets/flask@3596b1ab61 (2026-08-11). Data as JSON: /api/errors/0918783234736171. Report an issue: GitHub.

Appendix: source

Thrown at src/flask/ctx.py:466

        call teardown functions and signals.

        Typically, this is not used directly. Instead, use a ``with`` block
        to manage the context.

        This context must currently be the active context, otherwise a
        :exc:`RuntimeError` is raised. In some situations, such as streaming or
        testing, the context may have been pushed multiple times. It will only
        trigger cleanup once it has been popped as many times as it was pushed.
        Until then, it will remain the active context.

        :param exc: An unhandled exception that was raised while the context was
            active. Passed to teardown functions.

        .. versionchanged:: 0.9
            Added the ``exc`` argument.
        """
        if self._cv_token is None:
            raise RuntimeError(f"Cannot pop this context ({self!r}), it is not pushed.")

        ctx = _cv_app.get(None)

        if ctx is None or self._cv_token is None:
            raise RuntimeError(
                f"Cannot pop this context ({self!r}), there is no active context."
            )

        if ctx is not self:
            raise RuntimeError(
                f"Cannot pop this context ({self!r}), it is not the active"
                f" context ({ctx!r})."
            )

        self._push_count -= 1

        if self._push_count > 0:
            return

View on GitHub (pinned to 3596b1ab61)