Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the loader parameter does in yaml.load() function?

Tags:

yaml

pyyaml

I am writing a code to read YAML file as input. I see following options as Loader in yaml.load call: BaseLoader, SafeLoader, FullLoader, UnsafeLoader.

What do these options do? What does loading a full YAML language mean as mentioned in the following documentation page?

https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation

like image 410
Suzanno Hogwarts Avatar asked Dec 11 '19 04:12

Suzanno Hogwarts


1 Answers

In PyYAML the interface you call to load YAML is a function based (the load) function.

The implementation of the different stages of converting text in your YAML file into Python objects, scanning, parsing, composing and constructing are implemented as classes which PyYAML combines using composition into a loader.

There are different loaders, mostly because there are different constructors. E.g. the safe version of the loader will use the safe constructor, which will not create arbitrary Python objects, the base loader only loads strings (and not integers, floats, booleans, dates), etc.

In PyYAML you don't create an instance of the specific loader you want to use and then call one of its methods (or pass parameters to the intialisation). Instead you pass the type of object (i.e. its class) you want to create to the load() function as the Loader parameter. There are also some utility functions, like unsafe_load() that essentially do load(..., Loader=BaseLoader,...), etc., for you.


Please note that because of this, it is rather difficult to get any value back from the loading process except for the actual data constructed (let's say you are interested in the number of comments the scanner has thrown away): it is easy to subclass the scanner and add functionality, but you need to make an alternative loader that composes itself with this scanner and then at the end of your load(..., Loader=YourLoader) call that YourLoader is gone, so you cannot get to any attributes you added to your scanner (or parser, composer, constructor) instance to store the information.

The above describes the pure Python version, the C based loader works slightly different for the scanner/parser.

like image 82
Anthon Avatar answered Nov 15 '22 14:11

Anthon