9

I need to embed Python code into a YAML document. The document should preferably be portable (standard YAML), or at least parsable by Python (using PyYaml for example).

In fact I'm trying to include unmodified strings into yaml attributes. Indentations and new lines should be kept, so that embedded Python code could then be executed later.

I found the '>' but it removes newlines.

user2245644
  • 367
  • 2
  • 3
  • 10
  • What are you trying to do exactly? Save it as a string, or embed so that it can be executed? Or what? – Stefano Sanfilippo Jan 19 '14 at 16:05
  • Python source code is just text, and text is trivial to include in YAML. Or are you expecting the code to be run at some point (when exactly and how?) by the YAML processor? Then, not a snowball's chance in hell to be standard YAML. And why would you need that? –  Jan 19 '14 at 16:07
  • then how a literal string can be embeded into yaml, preserving indentation and new lines? – user2245644 Jan 19 '14 at 16:11
  • In several ways. [Check the spec](http://www.yaml.org/spec/1.2/spec.html#id2760844). –  Jan 19 '14 at 16:52

1 Answers1

17

You can use the literal scalar block style, introduced with |. For instance:

code: |
    def foo():
        print "foo"

    # we can include blank lines with no difficulty

    foo()

If you need to generate the file from code, then the yaml module does have functionality that allows you to control the block style: Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?

Thanks to @delnan for pointing me towards this very useful information.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490