| 12 | | == Introduction == |
| | 12 | == Installation == |
| | 13 | |
| | 14 | Download the source package '''PyYAML-3.04.tar.gz''' and unpack it. Go to the directory '''PyYAML-3.04''' |
| | 15 | and run |
| | 16 | {{{ |
| | 17 | $ python setup.py install |
| | 18 | }}} |
| | 19 | |
| | 20 | If you want to use LibYAML bindings, which are much faster than the pure Python version, you need to |
| | 21 | download and install [wiki:LibYAML] and [http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Pyrex]. |
| | 22 | Then you may build and install the bindings by executing |
| | 23 | {{{ |
| | 24 | $ python setup_with_libyaml.py install |
| | 25 | }}} |
| | 26 | |
| | 27 | In order to use [wiki:LibYAML] based parser and emitter, use the classes '''`CParser`''' and '''`CEmitter`'''. |
| | 28 | For instance, |
| | 29 | {{{ |
| | 30 | #!python |
| | 31 | from yaml import load, dump |
| | 32 | try: |
| | 33 | from yaml import CLoader as Loader |
| | 34 | from yaml import CDumper as Dumper |
| | 35 | except ImportError: |
| | 36 | from yaml import Loader, Dumper |
| | 37 | |
| | 38 | # ... |
| | 39 | |
| | 40 | data = load(stream, Loader=Loader) |
| | 41 | |
| | 42 | # ... |
| | 43 | |
| | 44 | output = dump(data, Dumper=Dumper) |
| | 45 | }}} |
| | 46 | Note that there are some subtle (but not really significant) differences between pure Python and [wiki:LibYAML] based parsers |
| | 47 | and emitters. |
| | 48 | |
| | 49 | |
| | 50 | == Frequently Asked Questions == |
| | 51 | |
| | 52 | === Dictionaries without nested collections are not dumped correctly === |
| | 53 | |
| | 54 | ''Why does |
| | 55 | {{{ |
| | 56 | #!python |
| | 57 | import yaml |
| | 58 | document = """ |
| | 59 | a: 1 |
| | 60 | b: |
| | 61 | c: 3 |
| | 62 | d: 4 |
| | 63 | """ |
| | 64 | print yaml.dump(yaml.load(document)) |
| | 65 | }}} |
| | 66 | give |
| | 67 | {{{ |
| | 68 | a: 1 |
| | 69 | b: {c: 3, d: 4} |
| | 70 | }}} |
| | 71 | (see #18, #24)?'' |
| | 72 | |
| | 73 | It's a correct output despite the fact that the style of the nested mapping is different. |
| | 74 | |
| | 75 | By default, PyYAML chooses the style of a collection depending on whether it has nested |
| | 76 | collections. If a collection has nested collections, it will be assigned the block style. |
| | 77 | Otherwise it will have the flow style. |
| | 78 | |
| | 79 | If you want collections to be always serialized in a block style, use the |
| | 80 | '''`default_flow_style`''' parameter of '''`dump()`'''. For instance, |
| | 81 | {{{ |
| | 82 | #!python |
| | 83 | >>> print yaml.dump(yaml.load(document), default_flow_style=False) |
| | 84 | a: 1 |
| | 85 | b: |
| | 86 | c: 3 |
| | 87 | d: 4 |
| | 88 | }}} |
| | 89 | |
| | 90 | |
| | 91 | == Tutorial == |