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:
ContextVar objects do not have __module__ and __qualname__ attributes, making straightforward pickling of Context objects impossible.
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
Contextobject.An ContextReducer object knows which context variables can be pickled.
- auto_register¶
If set to
True, callcopyreg.pickle()to declare this ContextReducer as “reduction” function forContextobjects, when theregister_contextvar()is called for the first time.
- factory_is_copy_context¶
If set to
True, usecontextvars.copy_context()to create a newContextobject 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
ContextReducerDeclare, that the context variable contextvar can be pickled.
- Parameters
contextvar (
ContextVar) – a context variablemodule (
ModuleTypeorstr) – the module object or the module name, where contextvar is declaredqualname (
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
TypeError – if contextvar is not an instance of
ContextVarValueError – if contextvar is not module.qualname.
- deregister_contextvar(contextvar)¶
Deregister contextvar from this
ContextReducerDeclare, 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
ContextReducerobject.The attributes are set as follows
- cvpickle.register_contextvar(contextvar, module, qualname=None, *, validate=True)¶
Register contextvar with
global_context_reducer
- cvpickle.deregister_contextvar(contextvar)¶
Deregister contextvar from
global_context_reducer