source: pyyaml/trunk/lib/yaml/__init__.py @ 152

Revision 152, 9.0 KB checked in by xi, 8 years ago (diff)

Add a way to override default style chosen by Representer: fix #9

Line 
1
2from error import *
3
4from tokens import *
5from events import *
6from nodes import *
7
8from loader import *
9from dumper import *
10
11def scan(stream, Loader=Loader):
12    """
13    Scan a YAML stream and produce scanning tokens.
14    """
15    loader = Loader(stream)
16    while loader.check_token():
17        yield loader.get_token()
18
19def parse(stream, Loader=Loader):
20    """
21    Parse a YAML stream and produce parsing events.
22    """
23    loader = Loader(stream)
24    while loader.check_event():
25        yield loader.get_event()
26
27def compose(stream, Loader=Loader):
28    """
29    Parse the first YAML document in a stream
30    and produce the corresponding representation tree.
31    """
32    loader = Loader(stream)
33    if loader.check_node():
34        return loader.get_node()
35
36def compose_all(stream, Loader=Loader):
37    """
38    Parse all YAML documents in a stream
39    and produce corresponsing representation trees.
40    """
41    loader = Loader(stream)
42    while loader.check_node():
43        yield loader.get_node()
44
45def load_all(stream, Loader=Loader):
46    """
47    Parse all YAML documents in a stream
48    and produce corresponding Python objects.
49    """
50    loader = Loader(stream)
51    while loader.check_data():
52        yield loader.get_data()
53
54def load(stream, Loader=Loader):
55    """
56    Parse the first YAML document in a stream
57    and produce the corresponding Python object.
58    """
59    loader = Loader(stream)
60    if loader.check_data():
61        return loader.get_data()
62
63def safe_load_all(stream):
64    """
65    Parse all YAML documents in a stream
66    and produce corresponding Python objects.
67    Resolve only basic YAML tags.
68    """
69    return load_all(stream, SafeLoader)
70
71def safe_load(stream):
72    """
73    Parse the first YAML document in a stream
74    and produce the corresponding Python object.
75    Resolve only basic YAML tags.
76    """
77    return load(stream, SafeLoader)
78
79def emit(events, stream=None, Dumper=Dumper,
80        canonical=None, indent=None, width=None,
81        allow_unicode=None, line_break=None):
82    """
83    Emit YAML parsing events into a stream.
84    If stream is None, return the produced string instead.
85    """
86    getvalue = None
87    if stream is None:
88        try:
89            from cStringIO import StringIO
90        except ImportError:
91            from StringIO import StringIO
92        stream = StringIO()
93        getvalue = stream.getvalue
94    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
95            allow_unicode=allow_unicode, line_break=line_break)
96    for event in events:
97        dumper.emit(event)
98    if getvalue:
99        return getvalue()
100
101def serialize_all(nodes, stream=None, Dumper=Dumper,
102        canonical=None, indent=None, width=None,
103        allow_unicode=None, line_break=None,
104        encoding='utf-8', explicit_start=None, explicit_end=None,
105        version=None, tags=None):
106    """
107    Serialize a sequence of representation trees into a YAML stream.
108    If stream is None, return the produced string instead.
109    """
110    getvalue = None
111    if stream is None:
112        try:
113            from cStringIO import StringIO
114        except ImportError:
115            from StringIO import StringIO
116        stream = StringIO()
117        getvalue = stream.getvalue
118    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
119            allow_unicode=allow_unicode, line_break=line_break,
120            encoding=encoding, version=version, tags=tags,
121            explicit_start=explicit_start, explicit_end=explicit_end)
122    dumper.open()
123    for node in nodes:
124        dumper.serialize(node)
125    dumper.close()
126    if getvalue:
127        return getvalue()
128
129def serialize(node, stream=None, Dumper=Dumper, **kwds):
130    """
131    Serialize a representation tree into a YAML stream.
132    If stream is None, return the produced string instead.
133    """
134    return serialize_all([node], stream, Dumper=Dumper, **kwds)
135
136def dump_all(documents, stream=None, Dumper=Dumper,
137        default_style=None, default_flow_style=None,
138        canonical=None, indent=None, width=None,
139        allow_unicode=None, line_break=None,
140        encoding='utf-8', explicit_start=None, explicit_end=None,
141        version=None, tags=None):
142    """
143    Serialize a sequence of Python objects into a YAML stream.
144    If stream is None, return the produced string instead.
145    """
146    getvalue = None
147    if stream is None:
148        try:
149            from cStringIO import StringIO
150        except ImportError:
151            from StringIO import StringIO
152        stream = StringIO()
153        getvalue = stream.getvalue
154    dumper = Dumper(stream, default_style=default_style,
155            default_flow_style=default_flow_style,
156            canonical=canonical, indent=indent, width=width,
157            allow_unicode=allow_unicode, line_break=line_break,
158            encoding=encoding, version=version, tags=tags,
159            explicit_start=explicit_start, explicit_end=explicit_end)
160    dumper.open()
161    for data in documents:
162        dumper.represent(data)
163    dumper.close()
164    if getvalue:
165        return getvalue()
166
167def dump(data, stream=None, Dumper=Dumper, **kwds):
168    """
169    Serialize a Python object into a YAML stream.
170    If stream is None, return the produced string instead.
171    """
172    return dump_all([data], stream, Dumper=Dumper, **kwds)
173
174def safe_dump_all(documents, stream=None, **kwds):
175    """
176    Serialize a sequence of Python objects into a YAML stream.
177    Produce only basic YAML tags.
178    If stream is None, return the produced string instead.
179    """
180    return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
181
182def safe_dump(data, stream=None, **kwds):
183    """
184    Serialize a Python object into a YAML stream.
185    Produce only basic YAML tags.
186    If stream is None, return the produced string instead.
187    """
188    return dump_all([data], stream, Dumper=SafeDumper, **kwds)
189
190def add_implicit_detector(tag, regexp, first=None,
191        Loader=Loader, Dumper=Dumper):
192    """
193    Add an implicit scalar detector.
194    If an implicit scalar value matches the given regexp,
195    the corresponding tag is assigned to the scalar.
196    first is a sequence of possible initial characters or None.
197    """
198    Loader.add_implicit_resolver(tag, regexp, first)
199    Dumper.add_implicit_resolver(tag, regexp, first)
200
201def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
202    """
203    Add a path based resolver for the given tag.
204    A path is a list of keys that forms a path
205    to a node in the representation tree.
206    Keys can be string values, integers, or None.
207    """
208    Loader.add_path_resolver(tag, path, kind)
209    Dumper.add_path_resolver(tag, path, kind)
210
211def add_constructor(tag, constructor, Loader=Loader):
212    """
213    Add a constructor for the given tag.
214    Constructor is a function that accepts a Loader instance
215    and a node object and produces the corresponding Python object.
216    """
217    Loader.add_constructor(tag, constructor)
218
219def add_multi_constructor(tag_prefix, multi_constructor, Loader=Loader):
220    """
221    Add a multi-constructor for the given tag prefix.
222    Multi-constructor is called for a node if its tag starts with tag_prefix.
223    Multi-constructor accepts a Loader instance, a tag suffix,
224    and a node object and produces the corresponding Python object.
225    """
226    Loader.add_multi_constructor(tag_prefix, multi_constructor)
227
228def add_representer(data_type, representer, Dumper=Dumper):
229    """
230    Add a representer for the given type.
231    Representer is a function accepting a Dumper instance
232    and an instance of the given data type
233    and producing the corresponding representation node.
234    """
235    Dumper.add_representer(data_type, representer)
236
237def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
238    """
239    Add a representer for the given type.
240    Multi-representer is a function accepting a Dumper instance
241    and an instance of the given data type or subtype
242    and producing the corresponding representation node.
243    """
244    Dumper.add_multi_representer(data_type, multi_representer)
245
246class YAMLObjectMetaclass(type):
247    """
248    The metaclass for YAMLObject.
249    """
250    def __init__(cls, name, bases, kwds):
251        super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
252        if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
253            cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
254            cls.yaml_dumper.add_representer(cls, cls.to_yaml)
255
256class YAMLObject(object):
257    """
258    An object that can dump itself to a YAML stream
259    and load itself from a YAML stream.
260    """
261
262    __metaclass__ = YAMLObjectMetaclass
263
264    yaml_loader = Loader
265    yaml_dumper = Dumper
266
267    yaml_tag = None
268    yaml_flow_style = None
269
270    def from_yaml(cls, loader, node):
271        """
272        Convert a representation node to a Python object.
273        """
274        return loader.construct_yaml_object(node, cls)
275    from_yaml = classmethod(from_yaml)
276
277    def to_yaml(cls, dumper, data):
278        """
279        Convert a Python object to a representation node.
280        """
281        return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
282                flow_style=cls.yaml_flow_style)
283    to_yaml = classmethod(to_yaml)
284
Note: See TracBrowser for help on using the repository browser.