После того, как мы скопируем несколько строк кода в строку документации для теста do c, есть ли ярлык для автоматического добавления «>>>» перед кодом?
Например, в следующем docstring, код doctest длинный, очень утомительно вручную добавлять '>>>' для каждой строки .
def iter_leaves_with_another(tree: Mapping, iter_with: Mapping, default: Callable = dict):
"""
Iterates through the leaves of the tree (represented by nested mappings), together with another mapping.
This method can be applied to construct a dictionary with the same structure as the `tree`, with some transformations on the values.
For example,
>>> import utilx.dict_ext as dx
>>> reconstruct = {}
>>> for d, k, v in dx.iter_leaves_with_another({
>>> 'a': 1,
>>> 'b': {'b1': 2,
>>> 'b2': {'b21': 3,
>>> 'b22': 4,
>>> 'b23': {'b231': 5}}},
>>> 'c': 6,
>>> 'd': {'d1': 7,
>>> 'd2': 8,
>>> 'd3': {},
>>> 'd4': {'d41': 9,
>>> 'd42': 10}}
>>> }, iter_with=reconstruct, default=dict):
>>> d[k] = v + 1
>>>
>>> # the following prints out the same tree structure, with all values being added by 1.
>>> # i.e. {'a': 2, 'b': {'b1': 3, 'b2': {'b21': 4, 'b22': 5, 'b23': {'b231': 6}}}, 'c': 7, 'd': {'d1': 8, 'd2': 9, 'd3': {}, 'd4': {'d41': 10, 'd42': 11}}}
>>> print(reconstruct)
:param tree: represented by a nested mapping.
:param iter_with: iterate through the leaves of the `tree` together with this mapping.
:param default: a callable that returns an object assigned to a key when it is not found in the `iter_with`.
:return: an iterator; yields a three-tuple at a time: 1) a sub-mapping in `iter_with` that corresponds to the current level in the `tree` being iterated through; 2) the key; 3) the value.
"""
for k, v in tree.items():
if isinstance(v, Mapping):
if k not in iter_with:
iter_with[k] = default()
yield from iter_leaves_with_another(tree=v, iter_with=iter_with[k], default=default)
else:
yield iter_with, k, v