yaml 变量引用_语法 - 如何从同一个YAML文件中的其他地方引用YAML“设置”?

您的示例无效仅仅是因为您选择了保留字符来启动标量。 如果您将self.d替换为其他非保留字符(我倾向于使用非ASCII字符,因为它们很少用作某些规范的一部分),您最终会得到完全合法的YAML:

paths:

root: /path/to/root/

patha: ♦root♦ + a

pathb: ♦root♦ + b

pathc: ♦root♦ + c

这将加载到您的解析器使用的语言中的映射的标准表示中,并且不会神奇地扩展任何内容。

为此,请使用本地默认对象类型,如以下Python程序中所示:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:

def __init__(self):

self.d = {}

def __repr__(self):

return repr(self.d).replace('ordereddict', 'Paths')

@staticmethod

def __yaml_in__(loader, data):

result = Paths()

loader.construct_mapping(data, result.d)

return result

@staticmethod

def __yaml_out__(dumper, self):

return dumper.represent_mapping('!Paths', self.d)

def __getitem__(self, key):

res = self.d[key]

return self.expand(res)

def expand(self, res):

try:

before, rest = res.split(u'♦', 1)

kw, rest = rest.split(u'♦ +', 1)

rest = rest.lstrip() # strip any spaces after "+"

# the lookup will throw the correct keyerror if kw is not found

# recursive call expand() on the tail if there are multiple

# parts to replace

return before + self.d[kw] + self.expand(rest)

except ValueError:

return res

yaml_str = """\

paths: !Paths

root: /path/to/root/

patha: ♦root♦ + a

pathb: ♦root♦ + b

pathc: ♦root♦ + c

"""

loader = yaml.RoundTripLoader

loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:

print(u'{} -> {}'.format(k, paths[k]))

将打印:

root -> /path/to/root/

pathc -> /path/to/root/c

扩展是在动态完成并处理嵌套定义,但您必须小心不要调用无限递归。

通过指定转储器,您可以从加载的数据中转储原始YAML,因为它具有动态扩展:

dumper = yaml.RoundTripDumper

dumper.add_representer(Paths, Paths.__yaml_out__)

print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

这将改变映射键排序。 如果那是你的问题制作self.d CommentedMap(从ruamel.yaml.comments.py导入)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值