| | 89 | |
| | 90 | PyYAML allows you to construct a Python object of any type. |
| | 91 | |
| | 92 | {{{ |
| | 93 | #!python |
| | 94 | >>> yaml.load(""" |
| | 95 | ... none: [~, null] |
| | 96 | ... bool: [true, false, on, off] |
| | 97 | ... int: 42 |
| | 98 | ... float: 3.14159 |
| | 99 | ... list: [LITE, RES_ACID, SUS_DEXT] |
| | 100 | ... dict: {hp: 13, sp: 5} |
| | 101 | ... """) |
| | 102 | |
| | 103 | {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, |
| | 104 | 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], 'dict': {'hp': 13, 'sp': 5}, |
| | 105 | 'bool': [True, False, True, False]} |
| | 106 | }}} |
| | 107 | |
| | 108 | Even instances of Python classes can be constructed using the '''`!!python/object`''' tag. |
| | 109 | {{{ |
| | 110 | #!python |
| | 111 | >>> class Hero: |
| | 112 | ... def __init__(self, name, hp, sp): |
| | 113 | ... self.name = name |
| | 114 | ... self.hp = hp |
| | 115 | ... self.sp = sp |
| | 116 | ... def __repr__(self): |
| | 117 | ... return "%s(name=%r, hp=%r, sp=%r)" % ( |
| | 118 | ... self.__class__.__name__, self.name, self.hp, self.sp) |
| | 119 | |
| | 120 | >>> yaml.load(""" |
| | 121 | ... !!python/object:__main__.Hero |
| | 122 | ... name: Welthyr Syxgon |
| | 123 | ... hp: 1200 |
| | 124 | ... sp: 0 |
| | 125 | ... """) |
| | 126 | |
| | 127 | Hero(name='Welthyr Syxgon', hp=1200, sp=0) |
| | 128 | }}} |
| | 129 | |
| | 130 | Note that the ability to construct an arbitrary Python object may be dangerous |
| | 131 | if you receive a YAML document from an untrusted source such as Internet. |
| | 132 | The function '''`yaml.safe_load`''' limits this ability to simple Python objects |
| | 133 | like integers or lists. |