I have a file with the following data:
classes:
- 9:00
- 10:20
- 12:10
(and so on up to 21:00)
I use python3 and yaml module to parse it. Precisely, the source is config = yaml.load (open (filename, 'r'))
. But then, when I print
config
, I get the following output for this part of data:
'classes': [540, 630, 730, 820, 910, 1000, 1090, 1180],
The values in the list are ints.
While previously, when I used python2 (and BaseLoader
for YAML), I got the values as strings, and I use them as such. BaseLoader
is now not acceptable since I want to read unicode strings from file, and it gives me byte-strings.
So, first, why pyyaml does parse my data as ints?
And, second, how do I prevent pyyaml from doing this? Is it possible to do that without changing data file (e.g. without adding !!str
)?
You should probably check the documentation of YAML
The colon are for mapping values.
I presume you want a string and not an integer, so you should double quote your strings.
The documentation of YAML is a bit difficult to "parse" so I can imagine you missed this little bit of info about colons:
And what you have there in your input is a sexagesimal and your
9:00
is considered to be similar to 9 minutes and 0 seconds, equalling a total of 540 seconds.Unfortunately this doesn't get constructed as some special Sexagesimal instance that can be used for calculations as if it were an integer but can be printed in its original form. Therefore, if you want to use this as a string internally you have to single quote them:
which is what you would get if you dump
{'classes': ['9:00', '10:20', '12:10']}
(and note that the unambiguousclasses
doesn't get any quotes).That the
BaseLoader
gives you strings is not surprising. TheBaseConstructor
that is used by theBaseLoader
handles any scalar as string, including integers, booleans and "your" sexagesimals:gives:
If you really don't want to use quotes, then you have to "reset" the implicit resolver for scalars that start with numbers:
gives you: