Defining with docstrings in yaml file: Parsing errors

2k views Asked by At

I am trying to parse the following yaml file:

\- api:

  api_first: """this is some docstring """

I basically want to use the triple quotes and have some statements within them. But when I use the yaml library it throws some errors for me

In [1]: import yaml

In [2]:with open('new.yaml') as f:
...:     dataMap = yaml.safe_load(f)
---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-2-2266b3e8606a> in <module>()
  1
  2 with open('new.yaml') as f:
  ----> 3     dataMap = yaml.safe_load(f)
/phaedrus/home/skorada/lib/python3.5/site-
 packages/yaml/parser.py in parse_block_sequence_entry(self)
391             token = self.peek_token()
392             raise ParserError("while parsing a block collection", 
self.marks[-1],
--> 393                     "expected <block end>, but found %r" % token.id, 
token.start_mark)
394         token = self.get_token()
395         event = SequenceEndEvent(token.start_mark, token.end_mark)

ParserError: while parsing a block collection
in "new.yaml", line 1, column 1
expected <block end>, but found '?'
in "new.yaml", line 2, column 1

Really not sure what the issue is?

1

There are 1 answers

2
Anthon On BEST ANSWER

There are no triple quotes in YAML. Your scalar can be single quoted, double quoted, non-quoted, or (in block-style) literal or folding.

If you want to emulate Python's triple-quoted strings and you don't have any control characters that need escaping (those do not include the newline character) you can use block style literal scalars:

api:

  api_first: |
     this is some docstring 
     with newlines after each line

. If you have control characters, you have to use double quoted scalars in YAML and either have newlines as \n or as double newlines within the double quotes.

Your """this is some docstring """ gets interpreted as three scalars on one line ("", "this is some docstring ", and "") and that is not valid YAML.

I assume the starting \ in your YAML is a typo.