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

Revision 275, 9.1 KB checked in by xi, 6 years ago (diff)

Use setuptools for setup.py. Dropped setup_with_libyaml.py; to build libyaml bindings, use --with-libyaml.

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