Is there any way to configure PyYAML so that I can get the line number associated with a given node? When procesing an input file, for example a configuration file, and I encounter a semantic error I would like to report what line number it is on.
I don't see anything immediately obvious in the docs, but there is this Mark
thing which seems to relate to line numbers.
The extensions I made in ruamel.yaml include an option to access line and column for collections (YAML: mapping, sequence, set, odict/Python dict, list, set, ordereddict):
import ruamel.yaml
data = ruamel.yaml.load("""
# example
- a
- e
- {x: 3}
- c
""", Loader=ruamel.yaml.RoundTripLoader)
assert data[2].lc.line == 3
assert data[2].lc.col == 2
both the line and column start counting at 0.
You are right about the Mark "thing", but the standard PyYAML loaders discard it when constructing the Python object. ruamel.yaml.RoundTripLoader
attaches the line and column information from the start Mark to its collection type (as it does with comments and block/flowstyle info.
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