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 ?
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.
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.
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.
In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With