当前位置: 代码迷 >> python >> 在 doctest 的文档字符串中的行前添加“>>>”的任何快捷方式?
  详细解决方案

在 doctest 的文档字符串中的行前添加“>>>”的任何快捷方式?

热度:113   发布时间:2023-07-16 10:57:34.0

我们把几行代码复制到docstring进行doc test后,有没有快捷方式可以自动在代码前面加上'>>>'?

比如下面的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

如果您想为文档字符串构建文档测试,您不应该只是将代码复制粘贴到文档字符串中并在前面添加>>> 添加>>>甚至不是正确的做法。 您不包括输出,并且您正在使用>>>提示...提示应该是。

Doctests 旨在看起来像一个交互式解释器会话。 要构建 doctest,实际运行一个交互式解释器会话并将转录本复制粘贴到 docstring 中。

这没有任何捷径,因为它可以使用替换轻松完成。 (转到Edit > Find > Replace ,或按Ctrl + R

  1. 启用RegEx,按下最右侧的图标(带有.*图标)到“搜索”字段。
  2. 按右起第二个图标启用In Selection
  3. 搜索字段中输入换行符\\n
  4. 替换字段中输入\\n>>>
  5. 用鼠标选择您想要的行,然后按全部替换

按全部替换之前填充所有字段后的屏幕截图。

按全部替换后的屏幕截图。

如果您需要某种程度的缩进,只需在\\n>>>之间的替换字段中添加必要的空格。