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

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.3]

When I try to load it with yaml.safe_load(file_object), I keep getting an error that reads:

yaml.constructor.ConstructorError:  could not determine a constructor for the tag 'tag:yaml.org,2002:python/tuple'

What needs to be done?



Solution 1:[1]

At least according to the PyYAML documentation:

The function yaml.safe_load limits this ability to simple Python objects like integers or lists.

The list, as you can see in the source, is somewhat more extensive but does not include tag:yaml.org,2002:python/tuple.

It appears that if you are generating a !!python/tuple type in your YAML file, you are using dump() as opposed to safe_dump(). If that's the case, you should probably switch to using load() in place of safe_load(), as files created by dump() are not guaranteed to be loadable by safe_load(). (See the description of safe_dump()).

Solution 2:[2]

For those, who are looking for an up-to-date answer.

Currently, this issue can be solved by using yaml.FullLoader.

import yaml
yaml_file = open("path/to/filename.yaml", 'r')
loaded_yaml = yaml.load(yaml_file, Loader=yaml.FullLoader)

Then entries marked as tuples as below will be correctly parsed without any issues.

!!python/tuple [0.3, 0.3 ,0.3]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niklas B.
Solution 2 cbakos