Fix allow_unicode (ticket:3).
[pyyaml/python3.git] / lib / yaml / representer.py
blob6fe74fceed985b3e033e72892e7d9855386041fe
2 __all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
3 'RepresenterError']
5 from error import *
6 from nodes import *
7 from detector import *
9 try:
10 import datetime
11 datetime_available = True
12 except ImportError:
13 datetime_available = False
15 try:
16 set
17 except NameError:
18 from sets import Set as set
20 class RepresenterError(YAMLError):
21 pass
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 = {}
33 def close(self):
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):
43 alias_key = None
44 else:
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]
49 if node is None:
50 raise RepresenterError("recursive objects are not allowed: %r" % native)
51 return node
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)
56 break
57 else:
58 if None in self.yaml_representers:
59 node = self.yaml_representers[None](self, native)
60 else:
61 node = ScalarNode(None, unicode(native))
62 if alias_key is not None:
63 self.represented_objects[alias_key] = node
64 return 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:
80 tag = None
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:
85 tag = None
86 value = []
87 for item in sequence:
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:
93 tag = None
94 value = {}
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)
100 else:
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):
107 return False
109 class SafeRepresenter(Detector, BaseRepresenter):
111 def ignore_aliases(self, native):
112 if native in [None, ()]:
113 return True
114 if isinstance(native, (str, unicode, bool, int, float)):
115 return True
117 def represent_none(self, native):
118 return self.represent_scalar(u'tag:yaml.org,2002:null',
119 u'null')
121 def represent_str(self, native):
122 encoding = None
123 try:
124 unicode(native, 'ascii')
125 encoding = 'ascii'
126 except UnicodeDecodeError:
127 try:
128 unicode(native, 'utf-8')
129 encoding = 'utf-8'
130 except UnicodeDecodeError:
131 pass
132 if encoding:
133 return self.represent_scalar(u'tag:yaml.org,2002:str',
134 unicode(native, encoding))
135 else:
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):
143 if native:
144 value = u'true'
145 else:
146 value = u'false'
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))
155 inf_value = 1e300000
156 nan_value = inf_value/inf_value
158 def represent_float(self, native):
159 if native == self.inf_value:
160 value = u'.inf'
161 elif native == -self.inf_value:
162 value = u'-.inf'
163 elif native == self.nan_value or native != native:
164 value = u'.nan'
165 else:
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)
171 for item in native:
172 if not isinstance(item, tuple) or len(item) != 2:
173 pairs = False
174 break
175 if not pairs:
176 return self.represent_sequence(u'tag:yaml.org,2002:seq', native)
177 value = []
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):
187 value = {}
188 for key in native:
189 value[key] = None
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):
249 pass