Welcome to cvpickle’s documentation!

cvpickle — make contextvars.Context picklable

Pickling of Context objects is not possible by default for two reasons, given in https://www.python.org/dev/peps/pep-0567/#making-context-objects-picklable:

  1. ContextVar objects do not have __module__ and __qualname__ attributes, making straightforward pickling of Context objects impossible.

  2. Not all context variables refer to picklable objects. Making a ContextVar picklable must be an opt-in.

The module cvpickle provides a reducer (class ContextReducer) for context objects. You have to register a ContextVar with the reducer to get it pickled.

For convenience, the module provides a global ContextReducer object in cvpickle.global_context_reducer and ContextVar (un-)registration functions cvpickle.register_contextvar() and cvpickle.deregister_contextvar()

A minimal example:

>>> import cvpickle
>>> import contextvars
>>> 
>>> my_context_var = contextvars.ContextVar("my_context_var")
>>> cvpickle.register_contextvar(my_context_var, __name__)
class cvpickle.ContextReducer(*, auto_register=False, factory_is_copy_context=False)

A ContextReducer object is a “reduction” function for a Context object.

An ContextReducer object knows which context variables can be pickled.

auto_register

If set to True, call copyreg.pickle() to declare this ContextReducer as “reduction” function for Context objects, when the register_contextvar() is called for the first time.

factory_is_copy_context

If set to True, use contextvars.copy_context() to create a new Context object upon unpickling. This way the unpickled context variables are added to the existing context variables.

register_contextvar(contextvar, module, qualname=None, *, validate=True)

Register contextvar with this ContextReducer

Declare, that the context variable contextvar can be pickled.

Parameters
  • contextvar (ContextVar) – a context variable

  • module (ModuleType or str) – the module object or the module name, where contextvar is declared

  • qualname (str) – the qualified name of contextvar in module. If unset, contextvar.name is used.

  • validate (boolean) – if true, check that contextvar can be accessed as module.qualname.

Raises
deregister_contextvar(contextvar)

Deregister contextvar from this ContextReducer

Declare, that the context variable contextvar can’t be pickled.

Parameters

contextvar (ContextVar) – a context variable

Raises

KeyError – if contextvar hasn’t been registered.

cvpickle.global_context_reducer

A global ContextReducer object.

The attributes are set as follows

cvpickle.register_contextvar(contextvar, module, qualname=None, *, validate=True)

Register contextvar with global_context_reducer

See ContextReducer.register_contextvar().

cvpickle.deregister_contextvar(contextvar)

Deregister contextvar from global_context_reducer

See ContextReducer.deregister_contextvar().

Indices and tables