Search code examples
pythonyamlpyyaml

What's the correct way to create a YAML document without a file?


I want to create a YAML file from scratch inside a python program (with PyYAML), to send it inside a HTTP request body. The closest thing I've found in the PyYAML docs is this:

import yaml
document = """
  a: 1
  b:
    c: 3
    d: 4
"""
yaml.load(document)
send_req(document)

However, I find it ugly and not very maintainable, so I would like to be able to do something like this:

document = {'a': 1, 'b': {'c': 3, 'd': 4}}
yaml.load(document)
send_req(document)

So I can modify its structure in a programmatic way, with variables and so.

How can I create a YAML document from a python object structure?


Solution

  • I think what you want is yaml.dump.

    document = {'a': 1, 'b': {'c': 3, 'd': 4}}
    print(yaml.dump(document))
    >>> a: 1
    b: {c: 3, d: 4}
    

    For simple Python objects you can even serialize .__dict__ directly:

    class MyClass(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    my_obj = MyClass(1, 2)
    print(yaml.dump(my_obj.__dict__))
    >>> {a: 1, b: 2}