### Navigation

- index
- modules |
- next |
- previous |
- home|
- search|
- API »
- The PyZMQ API »

# eventloop.stack_context

## Module: `eventloop.stack_context`

StackContext allows applications to maintain threadlocal-like state that follows execution as it moves to other execution contexts.

The motivating examples are to eliminate the need for explicit async_callback wrappers (as in tornado.web.RequestHandler), and to allow some additional context to be kept for logging.

This is slightly magic, but it’s an extension of the idea that an exception handler is a kind of stack-local state and when that stack is suspended and resumed in a new context that state needs to be preserved. StackContext shifts the burden of restoring that state from each call site (e.g. wrapping each AsyncHTTPClient callback in async_callback) to the mechanisms that transfer control from one context to another (e.g. AsyncHTTPClient itself, IOLoop, thread pools, etc).

Example usage:

    @contextlib.contextmanager
    def die_on_error():
        try:
            yield
        except:
            logging.error("exception in asynchronous operation",exc_info=True)
            sys.exit(1)

    with StackContext(die_on_error):
        # Any exception thrown here *or in callback and its desendents*
        # will cause the process to exit instead of spinning endlessly
        # in the ioloop.
        http_client.fetch(url, callback)
    ioloop.start()

## Functions

`zmq.eventloop.stack_context.``NullContext`(*args, **kwds)

  Resets the StackContext.

  Useful when creating a shared resource on demand (e.g. an AsyncHTTPClient) where the stack that caused the creating is not relevant to future operations.

`zmq.eventloop.stack_context.``StackContext`(*args, **kwds)

  Establishes the given context as a StackContext that will be transferred.

  Note that the parameter is a callable that returns a context manager, not the context itself. That is, where for a non-transferable context manager you would say

  > with my_context():

  StackContext takes the function itself rather than its result:
    with StackContext(my_context):

`zmq.eventloop.stack_context.``wrap`(fn)

  Returns a callable object that will resore the current StackContext when executed.

  Use this whenever saving a callback to be executed later in a different execution context (either in a different thread or asynchronously in the same thread).

### Navigation

- index
- modules |
- next |
- previous |
- home|
- search|
- API »
- The PyZMQ API »