Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python difference between yaml.load and yaml.safe_load

I am seeing that PyYaml, truncates zero's while loading from yaml file, if one uses: yaml.safe_load(stream).

It can be fixed, if one uses yaml.load(stream, Loader=yaml.BaseLoader), but is that advisable?

It works with yaml.load and zeros are not truncated.

I want to understand that would it be safe to switch to yaml.load instead of yaml.safe_load?

Example:

Test yaml content:

$cat test.yml
number: 5.10

Code:

$python -c 'import yaml, sys; content = yaml.safe_load(sys.stdin); 
print(content) ' < test.yml
{'number': 5.1}

<< It truncates the 0 at the end. But that is due to floating point value >>

whereas what I want is the exact number as is.

$python -c 'import yaml, sys; content = yaml.load(sys.stdin, 
Loader=yaml.BaseLoader); print(content) ' < test.yml
{u'number': u'5.10'}

Is that the correct approach to change it to yaml.load ?

like image 912
iDev Avatar asked Sep 16 '20 00:09

iDev


People also ask

What is YAML Safe_load?

Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.

What is a YAML loader?

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.

Is PyYAML same as YAML?

YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages.

What does YAML dump return?

In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.


Video Answer


1 Answers

yaml.safe_load(sys.stdin) just does yaml.load(sys.stdin, Loader=yaml.SafeLoader).

The facilities to execute arbitrary Python code (which makes loading unsafe) are implemented in yaml.Loader which is used by default. yaml.BaseLoader does not contain them. Therefore, if you use yaml.BaseLoader, loading will not execute arbitrary Python code (that is, unless you yourself register custom constructors with yaml.BaseLoader).

like image 130
flyx Avatar answered Sep 26 '22 05:09

flyx