You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义PyYAML SafeLoader仅为顶层字典添加行号?

仅为PyYAML最顶层字典添加行号的实现问题

我正在使用PyYAML,尝试为嵌套YAML结构中的字典添加行号,但仅希望添加到最顶层字典,示例如下:

- id: 123
  __line: 1
  links:
    - name: "abc"
    # 此处无需行号
    - name: "def"

有一个方案通过重写SafeLoader添加行号,但该方法会为所有层级的字典都添加__line字段。

我在相关讨论中询问如何仅对结构的最顶层应用此逻辑,用户@augurar给出了一个解决方案思路:

由于构造函数采用深度优先遍历,你可以添加一个属性来跟踪当前深度,并改写construct_object()以适当增减深度。如果你的场景需要处理锚点,还需要一些额外逻辑。

以下是我目前的尝试代码:

class SafeLineLoader(SafeLoader):
    def construct_mapping(self, node, deep=True):
        mapping = super(SafeLineLoader, self).construct_mapping(node, deep=deep)
        if node.get("depth") == 0:
            mapping["line"] = node.start_mark.line + 1
        print(node)
        return mapping

    def construct_object(self, node, deep=False, depth=0):
        return super().construct_object(node, deep=deep, depth=depth + 1)

但我遇到了如下错误:

return super().construct_object(node, deep=deep, depth=depth + 1)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BaseConstructor.construct_object() got an unexpected keyword argument 'depth'

我猜测这是因为PyYAML的construct_object函数不接受depth参数。这可能是关于包装类方法和添加新参数的Python基础问题,也可能是我尚未理解PyYAML库的架构。

内容的提问来源于stack exchange,提问作者V. Rubinetti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:45:02