Search code examples
pythonyamlpyyaml

pyyaml safe_load: how to ignore local tags


I am using yaml.safe_load() but I need to ignore a tag !v2 -- is there a way to do this but still use safe_load() ?


Solution

  • I figured it out, it's related to How can I add a python tuple to a YAML file using pyYAML?

    I just have to do this:

    • subclass yaml.SafeLoader
    • call add_constructor to assign !v2 to a custom construction method
    • in the custom construction method, do whatever is appropriate
    • use yaml.load(..., MyLoaderClass) instead of yaml.safe_load(...)

    and it works.

    class V2Loader(yaml.SafeLoader):
        def let_v2_through(self, node):
            return self.construct_mapping(node)
    V2Loader.add_constructor(
        u'!v2',
        V2Loader.let_v2_through)
    
       ....
    
    y = yaml.load(info, Loader=V2Loader)