gevent.contextvars – Cooperative contextvars

This module was added to Python 3.7. The gevent version is available on all supported versions of Python.

Context variables are like greenlet-local variables, just more inconvenient to use. They were designed to work around limitations in asyncio and are rarely needed by greenlet-based code.

The primary difference is that snapshots of the state of all context variables in a given greenlet can be taken, and later restored for execution; modifications to context variables are “scoped” to the duration that a particular context is active. (This state-restoration support is rarely useful for greenlets because instead of always running “tasks” sequentially within a single thread like asyncio does, greenlet-based code usually spawns new greenlets to handle each task.)

The gevent implementation is based on the Python reference implementation from PEP 567 and doesn’t have much optimization. In particular, setting context values isn’t constant time.

New in version 1.5a3.

class Context[source]

Bases: collections.abc.Mapping

Implementation of contextvars.Context

Creates an empty context.

copy()[source]

Return a shallow copy.

class ContextVar(name, default=<default value>)[source]

Bases: object

Implementation of contextvars.ContextVar.

class Token(context, var, old_value)[source]

Bases: object

Opaque implementation of contextvars.Token.

property old_value

A read-only attribute set to the value the variable had before the set() call, or to MISSING if the variable wasn’t set before.

property var

A read-only attribute pointing to the variable that created the token

copy_context()[source]

Return a shallow copy of the current context.

Next page: gevent.events – Publish/subscribe event infrastructure