Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyYAML getting line number of a node [duplicate]

Tags:

python

pyyaml

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.

like image 999
edA-qa mort-ora-y Avatar asked Nov 14 '22 09:11

edA-qa mort-ora-y


1 Answers

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.

like image 170
Anthon Avatar answered Dec 19 '22 20:12

Anthon