Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ?

like image 694
Jason S Avatar asked Oct 09 '15 23:10

Jason S


2 Answers

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)
like image 125
Markus Cozowicz Avatar answered Sep 25 '22 16:09

Markus Cozowicz


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)
like image 20
Jason S Avatar answered Sep 25 '22 16:09

Jason S