如何使用 ruamel.yaml.round_trip_load 保留引号而不因重复键而出错?

How to use ruamel.yaml.round_trip_load to preserve quotes and not get error for duplicate keys?

我有以下 test.yaml 文档:

components:
  schemas:
    description: 'ex1'
    description: 'ex2'

和以下读取 yaml 的 python 脚本:

import ruamel.yaml

ruamel.yaml.YAML().allow_duplicate_keys = True
def read_yaml_file(filename: str):
    with open(filename, 'r') as stream:
       
        my_yaml = ruamel.yaml.round_trip_load(stream, preserve_quotes=True)
        return my_yaml
      
my_yaml = read_yaml_file('test.yaml')

问题如何解决以下错误? (我不介意密钥是否被覆盖)

ruamel.yaml.constructor.DuplicateKeyError: while constructing a mapping
  in "test.yaml", line 3, column 5
found duplicate key "description" with value "ex2" (original value: "ex1")
  in "test.yaml", line 4, column 5

您将新样式 API 与旧 (PyYAML) 样式 API 混合在一起,这是不应该的。 您设置 .allow_duplicate_keysYAML() 实例会立即销毁 你做事,你应该使用它的 .load() 方法来加载你作为输入的非 YAML:

import sys
import ruamel.yaml

yaml_str = """\
components:
  schemas:
    description: 'ex1'
    description: 'ex2'
"""

yaml = ruamel.yaml.YAML()
yaml.allow_duplicate_keys = True
yaml.preserve_quotes = True
# yaml.indent(mapping=4, sequence=4, offset=2)
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)

给出:

components:
  schemas:
    description: 'ex1'

这意味着键 description 的值不会被覆盖,而是保留文件中该键的第一个值。