source: pyyaml/trunk/lib3/yaml/__init__.py @ 328

Revision 328, 8.7 KB checked in by xi, 5 years ago (diff)

Added basic support for Python 3 (Thanks idadesub(at)users(dot)sourceforge(dot)net).

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