Base Context¶
The base class for Context objects that include functions to validate a context.
- class disseminate.context.context.BaseContext(*args, **kwargs)¶
Bases:
dict
A context dict with entries used for rendering target documents.
Contexts are suppose to be data container dicts–i.e. there are no sophisticated processing or rendering functions. The available functions only manage the data and set of the context.
The BaseContext is basically a heritable dict. It keeps track of dict lineage and initial values so that it can be reset to its initialized state.
Note
I’ve tried different implementations, including a ChainMap-like inheritance. The problem with these is that key lookup and __contains__ lookup are relatively slow, compared to a standard dict. For this reason, I’ve decided to implement the BaseContext as a simple dict with values copied from a parent_context. The downside of this approach is that it’s more memory intensive, but this is mitigated to a great extended from creating shallow copies or weak references of parent_context entries.
- Parameters
- parent_contextOptional[dict]
A parent or template context.
- *args, **kwargstuple and dict
The entries to populate in the context dict.
Examples
>>> parent = BaseContext(a=1, b=[]) >>> child = BaseContext(parent_context=parent) >>> child['a'] 1 >>> child['a'] = 2 >>> child['a'] 2 >>> parent['a'] 1 >>> child['b'].append(1) >>> child['b'] [1] >>> parent['b'] []
- Attributes
- validation_typesDict[str, type]
A listing of entry keys and the types they should be. If None is listed as the type, then a type check will not be conducted.
- parent
BaseContext
A weakref to a BaseContext of a parent document.
- do_not_inheritSet[str]
The context keys that should not be accessed (inherited) from the parent context.
- exclude_from_resetSet[str]
The context entries that should not be removed when the context is reset.
- replaceSet[str]
The muttable context entries that should be replaced, rather than appended, from the parent context.
- _initial_valuesdict
A dict containing the initial values. Since this starts with an underscore, it is hidden when listing keys with the keys() function.
- _parent_context
Type[BaseContext]
A dict containing the parent context from which values may be inherited. Since this starts with an underscore, it is hidden when listing keys with the keys() function.
- filter(keys)¶
Create a new context with the entries copied for the given keys.
- Parameters
- keysIterable[str]
The keys for entries to include in the returned filtered BaseContext
- Returns
- copy
context.BaseContext
The filtered copy of the BaseContext.
- copy
- classmethod find_do_not_inherit()¶
Retrieve a union set for the do_not_inherit attribute of this class and all parent classes.
- Returns
- do_not_inheritSet[str]
A set of all attributes that should not be inherited by child class instances.
- is_valid(*keys, must_exist=True)¶
Validate the entries in the context dict.
This function checks that the keys denoted by the validate_types class attribute match the corresponding types for its values.
- Parameters
- keysOptional[Tuple[str]]
If specified, only the given keys will be checked if they’re in the validate_types class attribute. Otherwise all validate_types will be checked.
- must_existOptional[bool]
If True (default), then the entry must also exist in addition to having the correct type. If False, then entries can be missing in this dict that are listed in the validate_types class attribute.
- Returns
- validatedbool
True if the context is valid. False if the context is not valid
- load(string, strip_header=True, overwrite=True)¶
Load context entries from a string.
The load function interprets a string containing a dict in the format processed by
str_to_dict
. Additionally, this function parses header portions of strings delineated by 3 or more ‘-‘ characters, and only new entries entries that match the types of existing entries are inserted.- Parameters
- stringstr
The string to load into this context.
- strip_headerOptional[bool]
If True (default), the returned string will have the header removed.
- overwriteOptional[bool]
If True, allow existing entries in self to be overwritten by changes.
- Returns
- stringstr
The processed string with the header removed (if available) or just the string passed as an argument.
Examples
>>> context = BaseContext() >>> rest = context.load('test: 1') >>> print(context) BaseContext{test: 1}
- match_update(changes, keys=None, overwrite=True, level=1)¶
Update this context dict with changes by matching entry types.
Matched update behaves like a dict’s update method with these key differences:
If changes is a string, it is first converted to a dict.
Existing entries from changes are converted to the same type as the value in this dict. See examples below.
Mutable values are deep copied from the changes dict.
- Parameters
- changesUnion[str, dict,
BaseContext
] The changes to update into this context dict.
- keysOptional[Iterable[str]]
If specified, only update the given keys
- overwriteOptional[bool]
If True, allow existing entries in self to be overwritten by changes.
- levelOptional[int]
The level of recursion for this function.
- changesUnion[str, dict,
Notes
The matched update only updates entries for matching types and appends to nested mutables, like lists and dicts.
New entries from ‘changes’ are copied
If the change’s value has a ‘copy’ method, a copy is created with that method
Otherwise, the value is copied directly
Existing entries are converted to the type of the value in this context dict.
Lists, sets and dicts: A copy of the changes value is converted to the respective type and appended to this context dict’s list, set or dict.
Immutables are converted and added directly.
Examples
>>> orig = BaseContext(test = []) >>> orig.match_update(changes={'test': 'test'}) >>> orig['test'] ['test'] >>> orig.match_update(changes={'test': 'more changes'}) >>> orig['test'] ['more changes', 'test']
- property parent_context¶
The parent context.
- print()¶
Pretty print this context
- reset()¶
(Selectively) resets the context to its initial state.
The context is reset by removing items with keys not specified in the ‘exclude_from_clear’ class attribute.
Note
Entries in the parent_context are copied to this context. If the parent_context entry is a mutable, like a list or dict, then a copy of that mutable is created if a ‘copy’ method exists for that mutable. However, mutables within those mutables will still point to the original.
Examples
>>> l1, l2 = ['a'], ['b'] >>> context = BaseContext(l1=l1) >>> context['l2'] = l2 >>> context['l1'].append(1) >>> context['l2'].append(2) >>> context.reset() >>> context['l1'] == ['a'] # reset to original l1 True >>> 'l2' in context False
- exception disseminate.context.context.ContextException¶
Bases:
Exception
An exception raised when processing a BaseContext