Yaron Idan
Yaron Idan

Reputation: 6765

Trying to use yaml.load in python fails

I'm trying to understand the use of yaml.load() but even running this simple code won't work for me:

import yaml
document = """
  a: 1
  b:
    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?

Upvotes: 1

Views: 2080

Answers (1)

Anthon
Anthon

Reputation: 76912

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.

Upvotes: 1

Related Questions