如何自定义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
相关产品推荐
相关产品推荐

