Home > other >  How to access style of scalar used in a YAML value in ruamel?
How to access style of scalar used in a YAML value in ruamel?

Time:10-07

Take this example code:

from ruamel.yaml import YAML
import sys

yaml = YAML(pure=True)
yaml.allow_duplicate_keys = True
yaml.preserve_quotes = True
internal_dictionary = yaml.load("Key: \"value\"")
yaml.dump(code, sys.stdout)

Output:

Key: "value"

The internal_dictionary contains:

Key: value

But in the dump and the input file the value is between two ", ruamel knows this as it gets dumped correctly, is there I way where I can see it too in the phase where it is stored in the internal_dictionary without the two "?

CodePudding user response:

An exact answer would probably require a look at the code, but we see that the values have different data types.

The default type would be a string, but when the value is quoted, the type is a ruamel.yaml.scalarstring.DoubleQuotedScalarString with the "style" property.

rich inspect ruamel.yaml

CodePudding user response:

Assuming you load with yaml.preserve_quotes = True, if your scalar is unquoted and has no anchor (and is not recognised as a float, datetime, boolean, etc), the type of internal_dictionary['Key'] will be a normal Python string.

If the scalar is not an unquoted string , one of the types from ruamel/yaml/scalarstring.py is created: SingleQuotedScalarString, DoubleQuotedScalarString, LiteralScalaString, FoldedScalarString, PlainScalarString. These are all subclasses of ScalarString that handles the attachment of anchor for round-trip preservation.

SclarString is a subclass of str, which makes your output contain value if you inspect internal_dictionary.

So what you can do is e.g. test using isinstance(internal_dictionary['Key'], ruamel.yaml.scalarstring.DoubleQuotedScalarstring), or you can test on the 'style' attribute:

if internal_dictionary['Key'].style == '"':
  • Related