5

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.

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267
  • 2
    I was looking for the same thing and found this [other answer here on SO](http://stackoverflow.com/questions/13319067/parsing-yaml-return-with-line-number). – RocketR Dec 13 '12 at 16:35

1 Answers1

1

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.

Anthon
  • 69,918
  • 32
  • 186
  • 246