2 __all__
= ['BaseRepresenter', 'SafeRepresenter', 'Representer',
11 datetime_available
= True
13 datetime_available
= False
18 from sets
import Set
as set
20 class RepresenterError(YAMLError
):
23 class BaseRepresenter(BaseDetector
):
25 DEFAULT_SCALAR_TAG
= u
'tag:yaml.org,2002:str'
26 DEFAULT_SEQUENCE_TAG
= u
'tag:yaml.org,2002:seq'
27 DEFAULT_MAPPING_TAG
= u
'tag:yaml.org,2002:map'
29 def __init__(self
, serializer
):
30 self
.serializer
= serializer
31 self
.represented_objects
= {}
34 self
.serializer
.close()
36 def represent(self
, native
):
37 node
= self
.represent_object(native
)
38 self
.serializer
.serialize(node
)
39 self
.represented_objects
= {}
41 def represent_object(self
, native
):
42 if self
.ignore_aliases(native
):
45 alias_key
= id(native
)
46 if alias_key
is not None:
47 if alias_key
in self
.represented_objects
:
48 node
= self
.represented_objects
[alias_key
]
50 raise RepresenterError("recursive objects are not allowed: %r" % native
)
52 self
.represented_objects
[alias_key
] = None
53 for native_type
in type(native
).__mro
__:
54 if native_type
in self
.yaml_representers
:
55 node
= self
.yaml_representers
[native_type
](self
, native
)
58 if None in self
.yaml_representers
:
59 node
= self
.yaml_representers
[None](self
, native
)
61 node
= ScalarNode(None, unicode(native
))
62 if alias_key
is not None:
63 self
.represented_objects
[alias_key
] = node
66 def add_representer(cls
, native_type
, representer
):
67 if not 'yaml_representers' in cls
.__dict
__:
68 cls
.yaml_representers
= cls
.yaml_representers
.copy()
69 cls
.yaml_representers
[native_type
] = representer
70 add_representer
= classmethod(add_representer
)
72 yaml_representers
= {}
74 def represent_scalar(self
, tag
, value
, style
=None):
75 detected_tag
= self
.detect(value
)
76 if detected_tag
is None:
77 detected_tag
= self
.DEFAULT_SCALAR_TAG
78 implicit
= (tag
== detected_tag
)
79 if tag
== self
.DEFAULT_SCALAR_TAG
:
81 return ScalarNode(tag
, value
, implicit
=implicit
, style
=style
)
83 def represent_sequence(self
, tag
, sequence
, flow_style
=None):
84 if tag
== self
.DEFAULT_SEQUENCE_TAG
:
88 value
.append(self
.represent_object(item
))
89 return SequenceNode(tag
, value
, flow_style
=flow_style
)
91 def represent_mapping(self
, tag
, mapping
, flow_style
=None):
92 if tag
== self
.DEFAULT_MAPPING_TAG
:
95 if hasattr(mapping
, 'keys'):
96 for item_key
in mapping
.keys():
97 item_value
= mapping
[item_key
]
98 value
[self
.represent_object(item_key
)] = \
99 self
.represent_object(item_value
)
101 for item_key
, item_value
in mapping
:
102 value
[self
.represent_object(item_key
)] = \
103 self
.represent_object(item_value
)
104 return MappingNode(tag
, value
, flow_style
=flow_style
)
106 def ignore_aliases(self
, native
):
109 class SafeRepresenter(Detector
, BaseRepresenter
):
111 def ignore_aliases(self
, native
):
112 if native
in [None, ()]:
114 if isinstance(native
, (str, unicode, bool, int, float)):
117 def represent_none(self
, native
):
118 return self
.represent_scalar(u
'tag:yaml.org,2002:null',
121 def represent_str(self
, native
):
124 unicode(native
, 'ascii')
126 except UnicodeDecodeError:
128 unicode(native
, 'utf-8')
130 except UnicodeDecodeError:
133 return self
.represent_scalar(u
'tag:yaml.org,2002:str',
134 unicode(native
, encoding
))
136 return self
.represent_scalar(u
'tag:yaml.org,2002:binary',
137 unicode(native
.encode('base64')), style
='|')
139 def represent_unicode(self
, native
):
140 return self
.represent_scalar(u
'tag:yaml.org,2002:str', native
)
142 def represent_bool(self
, native
):
147 return self
.represent_scalar(u
'tag:yaml.org,2002:bool', value
)
149 def represent_int(self
, native
):
150 return self
.represent_scalar(u
'tag:yaml.org,2002:int', unicode(native
))
152 def represent_long(self
, native
):
153 return self
.represent_scalar(u
'tag:yaml.org,2002:int', unicode(native
))
156 nan_value
= inf_value
/inf_value
158 def represent_float(self
, native
):
159 if native
== self
.inf_value
:
161 elif native
== -self
.inf_value
:
163 elif native
== self
.nan_value
or native
!= native
:
166 value
= unicode(native
)
167 return self
.represent_scalar(u
'tag:yaml.org,2002:float', value
)
169 def represent_list(self
, native
):
170 pairs
= (len(native
) > 0)
172 if not isinstance(item
, tuple) or len(item
) != 2:
176 return self
.represent_sequence(u
'tag:yaml.org,2002:seq', native
)
178 for item_key
, item_value
in native
:
179 value
.append(self
.represent_mapping(u
'tag:yaml.org,2002:map',
180 [(item_key
, item_value
)]))
181 return SequenceNode(u
'tag:yaml.org,2002:pairs', value
)
183 def represent_dict(self
, native
):
184 return self
.represent_mapping(u
'tag:yaml.org,2002:map', native
)
186 def represent_set(self
, native
):
190 return self
.represent_mapping(u
'tag:yaml.org,2002:set', value
)
192 def represent_date(self
, native
):
193 value
= u
'%04d-%02d-%02d' % (native
.year
, native
.month
, native
.day
)
194 return self
.represent_scalar(u
'tag:yaml.org,2002:timestamp', value
)
196 def represent_datetime(self
, native
):
197 value
= u
'%04d-%02d-%02d %02d:%02d:%02d' \
198 % (native
.year
, native
.month
, native
.day
,
199 native
.hour
, native
.minute
, native
.second
)
200 if native
.microsecond
:
201 value
+= u
'.' + unicode(native
.microsecond
/1000000.0).split(u
'.')[1]
202 if native
.utcoffset():
203 value
+= unicode(native
.utcoffset())
204 return self
.represent_scalar(u
'tag:yaml.org,2002:timestamp', value
)
206 def represent_undefined(self
, native
):
207 raise RepresenterError("cannot represent an object: %s" % native
)
209 SafeRepresenter
.add_representer(type(None),
210 SafeRepresenter
.represent_none
)
212 SafeRepresenter
.add_representer(str,
213 SafeRepresenter
.represent_str
)
215 SafeRepresenter
.add_representer(unicode,
216 SafeRepresenter
.represent_unicode
)
218 SafeRepresenter
.add_representer(bool,
219 SafeRepresenter
.represent_bool
)
221 SafeRepresenter
.add_representer(int,
222 SafeRepresenter
.represent_int
)
224 SafeRepresenter
.add_representer(long,
225 SafeRepresenter
.represent_long
)
227 SafeRepresenter
.add_representer(float,
228 SafeRepresenter
.represent_float
)
230 SafeRepresenter
.add_representer(list,
231 SafeRepresenter
.represent_list
)
233 SafeRepresenter
.add_representer(dict,
234 SafeRepresenter
.represent_dict
)
236 SafeRepresenter
.add_representer(set,
237 SafeRepresenter
.represent_set
)
239 if datetime_available
:
240 SafeRepresenter
.add_representer(datetime
.date
,
241 SafeRepresenter
.represent_date
)
242 SafeRepresenter
.add_representer(datetime
.datetime
,
243 SafeRepresenter
.represent_datetime
)
245 SafeRepresenter
.add_representer(None,
246 SafeRepresenter
.represent_undefined
)
248 class Representer(SafeRepresenter
):