gevent.contextvars – Cooperative contextvars

This module was added to Python 3.7. The gevent version is available on all supported versions of Python. However, see an important note about gevent 20.9.

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.

Changed in version 20.9.0: On Python 3.7 and above, this module is no longer monkey-patched in place of the standard library version. gevent depends on greenlet 0.4.17 which includes support for context variables. This means that any number of greenlets can be running any number of asyncio tasks each with their own context variables. This module is only greenlet aware, not asyncio task aware, so its use is not recommended on Python 3.7 and above.

On previous versions of Python, this module continues to be a solution for backporting code. It is also available if you wish to use the contextvar API in a strictly greenlet-local manner.

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