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

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

Use Cython if available; added Python 3 support to _yaml.pyx.

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