context_base¶
Base class for objects holding a context-like set of options.
This module provides ContextBase, a small base class holding a context object - a namespace of option values - which can be cloned with overrides: subclasses use it to implement APIs where a set of options can be customized per-call without altering the shared defaults.
ContextBase
¶
A base class holding an overridable context of options.
The context is stored as a plain object - built via utils.make_object() - whose attributes are the option values.
Note that the clone is shallow: nested mutable values are shared between the clone and the context it was cloned from.
Example
from py_misc_utils import context_base
class Opt(context_base.ContextBase):
def set(self, **kwargs):
return self._new_ctx(**kwargs)
o = Opt(dict(v=1))
ctx = o.set(v=2, w=3)
# The new context is the current one, and it carries the overrides.
assert ctx.v == 2
assert ctx.w == 3
Source code in py_misc_utils/context_base.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |