pyyaml safe_load: how to ignore local tags

Extending the existing answer to support ignoring all unknown tags.

import yaml

class SafeLoaderIgnoreUnknown(yaml.SafeLoader):
    def ignore_unknown(self, node):
        return None 

SafeLoaderIgnoreUnknown.add_constructor(None, SafeLoaderIgnoreUnknown.ignore_unknown)

root = yaml.load(content, Loader=SafeLoaderIgnoreUnknown)

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)