How can I add a python tuple to a YAML file using pyYAML?

后端 未结 2 1925
花落未央
花落未央 2021-01-11 23:55

The title is fairly self-explanatory.

When I save a tuple to a YAML file, I get something that looks like this:

ambient:  !!python/tuple [0.3, 0.3 ,0         


        
2条回答
  •  不思量自难忘°
    2021-01-12 00:32

    In pyyaml, the SafeLoader does not include a loader for the python native types, only the types defined in the yaml spec. You can see the types for the SafeLoader and the Loader here in the interaction sample below.

    You can define a new Loader class that adds in the python tuple, but not other types, so it should still be pretty safe:

    import yaml
    
    class PrettySafeLoader(yaml.SafeLoader):
        def construct_python_tuple(self, node):
            return tuple(self.construct_sequence(node))
    
    PrettySafeLoader.add_constructor(
        u'tag:yaml.org,2002:python/tuple',
        PrettySafeLoader.construct_python_tuple)
    
    doc = yaml.dump(tuple("foo bar baaz".split()))
    print repr(doc)
    thing = yaml.load(doc, Loader=PrettySafeLoader)
    print thing
    

    resulting in:

    '!!python/tuple [foo, bar, baaz]\n'
    ('foo', 'bar', 'baaz')
    

    See below for the constructors associated with the SafeLoader and the Loader classes.

    >>> yaml.SafeLoader.yaml_constructors
    {None: ,
     u'tag:yaml.org,2002:binary': ,
     u'tag:yaml.org,2002:bool': ,
     u'tag:yaml.org,2002:float': ,
     u'tag:yaml.org,2002:int': ,
     u'tag:yaml.org,2002:map': ,
     u'tag:yaml.org,2002:null': ,
     u'tag:yaml.org,2002:omap': ,
     u'tag:yaml.org,2002:pairs': ,
     u'tag:yaml.org,2002:seq': ,
     u'tag:yaml.org,2002:set': ,
     u'tag:yaml.org,2002:str': ,
     u'tag:yaml.org,2002:timestamp': }
    
    >>> yaml.Loader.yaml_constructors
    {None: ,
     u'tag:yaml.org,2002:binary': ,
     u'tag:yaml.org,2002:bool': ,
     u'tag:yaml.org,2002:float': ,
     u'tag:yaml.org,2002:int': ,
     u'tag:yaml.org,2002:map': ,
     u'tag:yaml.org,2002:null': ,
     u'tag:yaml.org,2002:omap': ,
     u'tag:yaml.org,2002:pairs': ,
     u'tag:yaml.org,2002:python/bool': ,
     u'tag:yaml.org,2002:python/complex': ,
     u'tag:yaml.org,2002:python/dict': ,
     u'tag:yaml.org,2002:python/float': ,
     u'tag:yaml.org,2002:python/int': ,
     u'tag:yaml.org,2002:python/list': ,
     u'tag:yaml.org,2002:python/long': ,
     u'tag:yaml.org,2002:python/none': ,
     u'tag:yaml.org,2002:python/str': ,
     u'tag:yaml.org,2002:python/tuple': ,
     u'tag:yaml.org,2002:python/unicode': ,
     u'tag:yaml.org,2002:seq': ,
     u'tag:yaml.org,2002:set': ,
     u'tag:yaml.org,2002:str': ,
     u'tag:yaml.org,2002:timestamp': }
    

提交回复
热议问题