那你的例子是無效的只有,因爲你選擇了保留字符與開始你的標量。如果更換*
與其他一些非預留(我傾向於使用非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
進口)
**另請參閱:** https://stackoverflow.com/a/41620747/42223 – dreftymac 2017-10-02 19:42:51