close

最近用 pyyaml 想要讀/寫 yaml 檔案

沒想到居然遇到問題 yaml.constructor.ConstructorError: could not determine a constructor for the tag '!Ref'

看了下 yaml 那行 Value: !Ref "https://www.google.com.tw/"

原來是讀不懂 !Ref 需要自定義 Ref yaml object 讓它讀懂

import yaml
class Ref(yaml.YAMLObject):
    yaml_tag = '!Ref'
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return f'{self.yaml_tag} "{self.val}"'

    @classmethod
    def from_yaml(cls, loader, node):
        return cls(node.value)

 

讀懂後寫回去檔案的話還需要加 function 跟 yaml 說怎麼呈現

class Ref(yaml.YAMLObject):
    ...
    @classmethod
    def ref_representer(cls, dumper, data):
        return dumper.represent_scalar(cls.yaml_tag, data.val)

yaml.add_representer(Ref, Ref.ref_representer)

 

ref: https://github.com/yaml/pyyaml/issues/266

ref2: https://stackoverflow.com/questions/65820633/dumping-custom-class-objects-to-a-yaml-file

https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JohnDX 的頭像
    JohnDX

    我要回家想一想~

    JohnDX 發表在 痞客邦 留言(0) 人氣()