Yaron Idan Yaron Idan - 1 year ago 84
YAML Question

Trying to use yaml.load in python fails

I'm trying to understand the use of

but even running this simple code won't work for me:

import yaml
document = """
a: 1
c: 3
d: 4
print yaml.dump(yaml.load(document), default_flow_style=False)

When I execute this script is gives the following error -
AttributeError: 'module' object has no attribute 'dump'

This code was taken from the PyYAML documentation (http://pyyaml.org/wiki/PyYAMLDocumentation).

What am I missing here? How can I learn how to work with YAML in Python?

Answer Source

You called your example yaml.py and as such your test program is imported with the import yaml statement, and it doesn't have a dump routine. Just rename your yaml.py to something like test_yaml.py.

You should also use:

import sys

yaml.dump(yaml.load(document, sys.stdout, default_flow_style=False)

as not providing a stream as the second parameter to dump() causes the output to first be written to a StringIO() object, then to be retrieved by .getvalue() on that object, and then written out to sys.stdout. It is faster to do the latter directly.