Show More
@@ -1,503 +1,503 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Robert Kern |
|
7 | * Robert Kern | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2010, IPython Development Team. |
|
11 | # Copyright (c) 2010, IPython Development Team. | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
14 | # | |
15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
15 | # The full license is in the file COPYING.txt, distributed with this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | # Stdlib imports |
|
22 | # Stdlib imports | |
23 | import abc |
|
23 | import abc | |
24 | # We must use StringIO, as cStringIO doesn't handle unicode properly. |
|
24 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
25 | from StringIO import StringIO |
|
25 | from StringIO import StringIO | |
26 |
|
26 | |||
27 | # Our own imports |
|
27 | # Our own imports | |
28 | from IPython.config.configurable import Configurable |
|
28 | from IPython.config.configurable import Configurable | |
29 | from IPython.external import pretty |
|
29 | from IPython.external import pretty | |
30 | from IPython.utils.traitlets import Bool, Dict, Int, Str |
|
30 | from IPython.utils.traitlets import Bool, Dict, Int, Str | |
31 |
|
31 | |||
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # The main DisplayFormatter class |
|
34 | # The main DisplayFormatter class | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | class DisplayFormatter(Configurable): |
|
38 | class DisplayFormatter(Configurable): | |
39 |
|
39 | |||
40 | # When set to true only the default plain text formatter will be used. |
|
40 | # When set to true only the default plain text formatter will be used. | |
41 | plain_text_only = Bool(False, config=True) |
|
41 | plain_text_only = Bool(False, config=True) | |
42 |
|
42 | |||
43 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
43 | # A dict of formatter whose keys are format types (MIME types) and whose | |
44 | # values are subclasses of BaseFormatter. |
|
44 | # values are subclasses of BaseFormatter. | |
45 | formatters = Dict(config=True) |
|
45 | formatters = Dict(config=True) | |
46 | def _formatters_default(self): |
|
46 | def _formatters_default(self): | |
47 | """Activate the default formatters.""" |
|
47 | """Activate the default formatters.""" | |
48 | formatter_classes = [ |
|
48 | formatter_classes = [ | |
49 | PlainTextFormatter, |
|
49 | PlainTextFormatter, | |
50 | HTMLFormatter, |
|
50 | HTMLFormatter, | |
51 | SVGFormatter, |
|
51 | SVGFormatter, | |
52 | PNGFormatter, |
|
52 | PNGFormatter, | |
53 | LatexFormatter, |
|
53 | LatexFormatter, | |
54 | JSONFormatter |
|
54 | JSONFormatter | |
55 | ] |
|
55 | ] | |
56 | d = {} |
|
56 | d = {} | |
57 | for cls in formatter_classes: |
|
57 | for cls in formatter_classes: | |
58 | f = cls(config=self.config) |
|
58 | f = cls(config=self.config) | |
59 | d[f.format_type] = f |
|
59 | d[f.format_type] = f | |
60 | return d |
|
60 | return d | |
61 |
|
61 | |||
62 | def format(self, obj, include=None, exclude=None): |
|
62 | def format(self, obj, include=None, exclude=None): | |
63 | """Return a format data dict for an object. |
|
63 | """Return a format data dict for an object. | |
64 |
|
64 | |||
65 | By default all format types will be computed. |
|
65 | By default all format types will be computed. | |
66 |
|
66 | |||
67 | The following MIME types are currently implemented: |
|
67 | The following MIME types are currently implemented: | |
68 |
|
68 | |||
69 | * text/plain |
|
69 | * text/plain | |
70 | * text/html |
|
70 | * text/html | |
71 | * text/latex |
|
71 | * text/latex | |
72 | * application/json |
|
72 | * application/json | |
73 | * image/png |
|
73 | * image/png | |
74 | * immage/svg+xml |
|
74 | * immage/svg+xml | |
75 |
|
75 | |||
76 | Parameters |
|
76 | Parameters | |
77 | ---------- |
|
77 | ---------- | |
78 | obj : object |
|
78 | obj : object | |
79 | The Python object whose format data will be computed. |
|
79 | The Python object whose format data will be computed. | |
|
80 | include : list or tuple, optional | |||
|
81 | A list of format type strings (MIME types) to include in the | |||
|
82 | format data dict. If this is set *only* the format types included | |||
|
83 | in this list will be computed. | |||
|
84 | exclude : list or tuple, optional | |||
|
85 | A list of format type string (MIME types) to exclue in the format | |||
|
86 | data dict. If this is set all format types will be computed, | |||
|
87 | except for those included in this argument. | |||
80 |
|
88 | |||
81 | Returns |
|
89 | Returns | |
82 | ------- |
|
90 | ------- | |
83 | format_dict : dict |
|
91 | format_dict : dict | |
84 | A dictionary of key/value pairs, one or each format that was |
|
92 | A dictionary of key/value pairs, one or each format that was | |
85 | generated for the object. The keys are the format types, which |
|
93 | generated for the object. The keys are the format types, which | |
86 | will usually be MIME type strings and the values and JSON'able |
|
94 | will usually be MIME type strings and the values and JSON'able | |
87 | data structure containing the raw data for the representation in |
|
95 | data structure containing the raw data for the representation in | |
88 | that format. |
|
96 | that format. | |
89 | include : list or tuple, optional |
|
|||
90 | A list of format type strings (MIME types) to include in the |
|
|||
91 | format data dict. If this is set *only* the format types included |
|
|||
92 | in this list will be computed. |
|
|||
93 | exclude : list or tuple, optional |
|
|||
94 | A list of format type string (MIME types) to exclue in the format |
|
|||
95 | data dict. If this is set all format types will be computed, |
|
|||
96 | except for those included in this argument. |
|
|||
97 | """ |
|
97 | """ | |
98 | format_dict = {} |
|
98 | format_dict = {} | |
99 |
|
99 | |||
100 | # If plain text only is active |
|
100 | # If plain text only is active | |
101 | if self.plain_text_only: |
|
101 | if self.plain_text_only: | |
102 | formatter = self.formatters['text/plain'] |
|
102 | formatter = self.formatters['text/plain'] | |
103 | try: |
|
103 | try: | |
104 | data = formatter(obj) |
|
104 | data = formatter(obj) | |
105 | except: |
|
105 | except: | |
106 | # FIXME: log the exception |
|
106 | # FIXME: log the exception | |
107 | raise |
|
107 | raise | |
108 | if data is not None: |
|
108 | if data is not None: | |
109 | format_dict['text/plain'] = data |
|
109 | format_dict['text/plain'] = data | |
110 | return format_dict |
|
110 | return format_dict | |
111 |
|
111 | |||
112 | for format_type, formatter in self.formatters.items(): |
|
112 | for format_type, formatter in self.formatters.items(): | |
113 | if include is not None: |
|
113 | if include is not None: | |
114 | if format_type not in include: |
|
114 | if format_type not in include: | |
115 | continue |
|
115 | continue | |
116 | if exclude is not None: |
|
116 | if exclude is not None: | |
117 | if format_type in exclude: |
|
117 | if format_type in exclude: | |
118 | continue |
|
118 | continue | |
119 | try: |
|
119 | try: | |
120 | data = formatter(obj) |
|
120 | data = formatter(obj) | |
121 | except: |
|
121 | except: | |
122 | # FIXME: log the exception |
|
122 | # FIXME: log the exception | |
123 | raise |
|
123 | raise | |
124 | if data is not None: |
|
124 | if data is not None: | |
125 | format_dict[format_type] = data |
|
125 | format_dict[format_type] = data | |
126 | return format_dict |
|
126 | return format_dict | |
127 |
|
127 | |||
128 | @property |
|
128 | @property | |
129 | def format_types(self): |
|
129 | def format_types(self): | |
130 | """Return the format types (MIME types) of the active formatters.""" |
|
130 | """Return the format types (MIME types) of the active formatters.""" | |
131 | return self.formatters.keys() |
|
131 | return self.formatters.keys() | |
132 |
|
132 | |||
133 |
|
133 | |||
134 | #----------------------------------------------------------------------------- |
|
134 | #----------------------------------------------------------------------------- | |
135 | # Formatters for specific format types (text, html, svg, etc.) |
|
135 | # Formatters for specific format types (text, html, svg, etc.) | |
136 | #----------------------------------------------------------------------------- |
|
136 | #----------------------------------------------------------------------------- | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | class FormatterABC(object): |
|
139 | class FormatterABC(object): | |
140 | """ Abstract base class for Formatters. |
|
140 | """ Abstract base class for Formatters. | |
141 |
|
141 | |||
142 | A formatter is a callable class that is responsible for computing the |
|
142 | A formatter is a callable class that is responsible for computing the | |
143 | raw format data for a particular format type (MIME type). For example, |
|
143 | raw format data for a particular format type (MIME type). For example, | |
144 | an HTML formatter would have a format type of `text/html` and would return |
|
144 | an HTML formatter would have a format type of `text/html` and would return | |
145 | the HTML representation of the object when called. |
|
145 | the HTML representation of the object when called. | |
146 | """ |
|
146 | """ | |
147 | __metaclass__ = abc.ABCMeta |
|
147 | __metaclass__ = abc.ABCMeta | |
148 |
|
148 | |||
149 | # The format type of the data returned, usually a MIME type. |
|
149 | # The format type of the data returned, usually a MIME type. | |
150 | format_type = 'text/plain' |
|
150 | format_type = 'text/plain' | |
151 |
|
151 | |||
152 | # Is the formatter enabled... |
|
152 | # Is the formatter enabled... | |
153 | enabled = True |
|
153 | enabled = True | |
154 |
|
154 | |||
155 | @abc.abstractmethod |
|
155 | @abc.abstractmethod | |
156 | def __call__(self, obj): |
|
156 | def __call__(self, obj): | |
157 | """Return a JSON'able representation of the object. |
|
157 | """Return a JSON'able representation of the object. | |
158 |
|
158 | |||
159 | If the object cannot be formatted by this formatter, then return None |
|
159 | If the object cannot be formatted by this formatter, then return None | |
160 | """ |
|
160 | """ | |
161 | try: |
|
161 | try: | |
162 | return repr(obj) |
|
162 | return repr(obj) | |
163 | except TypeError: |
|
163 | except TypeError: | |
164 | return None |
|
164 | return None | |
165 |
|
165 | |||
166 |
|
166 | |||
167 | class BaseFormatter(Configurable): |
|
167 | class BaseFormatter(Configurable): | |
168 | """A base formatter class that is configurable. |
|
168 | """A base formatter class that is configurable. | |
169 |
|
169 | |||
170 | This formatter should usually be used as the base class of all formatters. |
|
170 | This formatter should usually be used as the base class of all formatters. | |
171 | It is a traited :class:`Configurable` class and includes an extensible |
|
171 | It is a traited :class:`Configurable` class and includes an extensible | |
172 | API for users to determine how their objects are formatted. The following |
|
172 | API for users to determine how their objects are formatted. The following | |
173 | logic is used to find a function to format an given object. |
|
173 | logic is used to find a function to format an given object. | |
174 |
|
174 | |||
175 | 1. The object is introspected to see if it has a method with the name |
|
175 | 1. The object is introspected to see if it has a method with the name | |
176 | :attr:`print_method`. If is does, that object is passed to that method |
|
176 | :attr:`print_method`. If is does, that object is passed to that method | |
177 | for formatting. |
|
177 | for formatting. | |
178 | 2. If no print method is found, three internal dictionaries are consulted |
|
178 | 2. If no print method is found, three internal dictionaries are consulted | |
179 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
179 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
180 | and :attr:`deferred_printers`. |
|
180 | and :attr:`deferred_printers`. | |
181 |
|
181 | |||
182 | Users should use these dictionarie to register functions that will be used |
|
182 | Users should use these dictionarie to register functions that will be used | |
183 | to compute the format data for their objects (if those objects don't have |
|
183 | to compute the format data for their objects (if those objects don't have | |
184 | the special print methods). The easiest way of using these dictionaries |
|
184 | the special print methods). The easiest way of using these dictionaries | |
185 | is through the :meth:`for_type` and :meth:`for_type_by_name` methods. |
|
185 | is through the :meth:`for_type` and :meth:`for_type_by_name` methods. | |
186 |
|
186 | |||
187 | If no function/callable is found to compute the format data, ``None`` is |
|
187 | If no function/callable is found to compute the format data, ``None`` is | |
188 | returned and this format type is not used. |
|
188 | returned and this format type is not used. | |
189 | """ |
|
189 | """ | |
190 |
|
190 | |||
191 | format_type = Str('text/plain') |
|
191 | format_type = Str('text/plain') | |
192 |
|
192 | |||
193 | enabled = Bool(True, config=True) |
|
193 | enabled = Bool(True, config=True) | |
194 |
|
194 | |||
195 | print_method = Str('__repr__') |
|
195 | print_method = Str('__repr__') | |
196 |
|
196 | |||
197 | # The singleton printers. |
|
197 | # The singleton printers. | |
198 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
198 | # Maps the IDs of the builtin singleton objects to the format functions. | |
199 | singleton_printers = Dict(config=True) |
|
199 | singleton_printers = Dict(config=True) | |
200 | def _singleton_printers_default(self): |
|
200 | def _singleton_printers_default(self): | |
201 | return {} |
|
201 | return {} | |
202 |
|
202 | |||
203 | # The type-specific printers. |
|
203 | # The type-specific printers. | |
204 | # Map type objects to the format functions. |
|
204 | # Map type objects to the format functions. | |
205 | type_printers = Dict(config=True) |
|
205 | type_printers = Dict(config=True) | |
206 | def _type_printers_default(self): |
|
206 | def _type_printers_default(self): | |
207 | return {} |
|
207 | return {} | |
208 |
|
208 | |||
209 | # The deferred-import type-specific printers. |
|
209 | # The deferred-import type-specific printers. | |
210 | # Map (modulename, classname) pairs to the format functions. |
|
210 | # Map (modulename, classname) pairs to the format functions. | |
211 | deferred_printers = Dict(config=True) |
|
211 | deferred_printers = Dict(config=True) | |
212 | def _deferred_printers_default(self): |
|
212 | def _deferred_printers_default(self): | |
213 | return {} |
|
213 | return {} | |
214 |
|
214 | |||
215 | def __call__(self, obj): |
|
215 | def __call__(self, obj): | |
216 | """Compute the format for an object.""" |
|
216 | """Compute the format for an object.""" | |
217 | if self.enabled: |
|
217 | if self.enabled: | |
218 | obj_id = id(obj) |
|
218 | obj_id = id(obj) | |
219 | try: |
|
219 | try: | |
220 | obj_class = getattr(obj, '__class__', None) or type(obj) |
|
220 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
221 | if hasattr(obj_class, self.print_method): |
|
221 | if hasattr(obj_class, self.print_method): | |
222 | printer = getattr(obj_class, self.print_method) |
|
222 | printer = getattr(obj_class, self.print_method) | |
223 | return printer(obj) |
|
223 | return printer(obj) | |
224 | try: |
|
224 | try: | |
225 | printer = self.singleton_printers[obj_id] |
|
225 | printer = self.singleton_printers[obj_id] | |
226 | except (TypeError, KeyError): |
|
226 | except (TypeError, KeyError): | |
227 | pass |
|
227 | pass | |
228 | else: |
|
228 | else: | |
229 | return printer(obj) |
|
229 | return printer(obj) | |
230 | for cls in pretty._get_mro(obj_class): |
|
230 | for cls in pretty._get_mro(obj_class): | |
231 | if cls in self.type_printers: |
|
231 | if cls in self.type_printers: | |
232 | return self.type_printers[cls](obj) |
|
232 | return self.type_printers[cls](obj) | |
233 | else: |
|
233 | else: | |
234 | printer = self._in_deferred_types(cls) |
|
234 | printer = self._in_deferred_types(cls) | |
235 | if printer is not None: |
|
235 | if printer is not None: | |
236 | return printer(obj) |
|
236 | return printer(obj) | |
237 | return None |
|
237 | return None | |
238 | except Exception: |
|
238 | except Exception: | |
239 | pass |
|
239 | pass | |
240 | else: |
|
240 | else: | |
241 | return None |
|
241 | return None | |
242 |
|
242 | |||
243 | def for_type(self, typ, func): |
|
243 | def for_type(self, typ, func): | |
244 | """Add a format function for a given type. |
|
244 | """Add a format function for a given type. | |
245 |
|
245 | |||
246 | Parameteres |
|
246 | Parameteres | |
247 | ----------- |
|
247 | ----------- | |
248 | typ : class |
|
248 | typ : class | |
249 | The class of the object that will be formatted using `func`. |
|
249 | The class of the object that will be formatted using `func`. | |
250 | func : callable |
|
250 | func : callable | |
251 | The callable that will be called to compute the format data. The |
|
251 | The callable that will be called to compute the format data. The | |
252 | call signature of this function is simple, it must take the |
|
252 | call signature of this function is simple, it must take the | |
253 | object to be formatted and return the raw data for the given |
|
253 | object to be formatted and return the raw data for the given | |
254 | format. Subclasses may use a different call signature for the |
|
254 | format. Subclasses may use a different call signature for the | |
255 | `func` argument. |
|
255 | `func` argument. | |
256 | """ |
|
256 | """ | |
257 | oldfunc = self.type_printers.get(typ, None) |
|
257 | oldfunc = self.type_printers.get(typ, None) | |
258 | if func is not None: |
|
258 | if func is not None: | |
259 | # To support easy restoration of old printers, we need to ignore |
|
259 | # To support easy restoration of old printers, we need to ignore | |
260 | # Nones. |
|
260 | # Nones. | |
261 | self.type_printers[typ] = func |
|
261 | self.type_printers[typ] = func | |
262 | return oldfunc |
|
262 | return oldfunc | |
263 |
|
263 | |||
264 | def for_type_by_name(self, type_module, type_name, func): |
|
264 | def for_type_by_name(self, type_module, type_name, func): | |
265 | """Add a format function for a type specified by the full dotted |
|
265 | """Add a format function for a type specified by the full dotted | |
266 | module and name of the type, rather than the type of the object. |
|
266 | module and name of the type, rather than the type of the object. | |
267 |
|
267 | |||
268 | Parameters |
|
268 | Parameters | |
269 | ---------- |
|
269 | ---------- | |
270 | type_module : str |
|
270 | type_module : str | |
271 | The full dotted name of the module the type is defined in, like |
|
271 | The full dotted name of the module the type is defined in, like | |
272 | ``numpy``. |
|
272 | ``numpy``. | |
273 | type_name : str |
|
273 | type_name : str | |
274 | The name of the type (the class name), like ``dtype`` |
|
274 | The name of the type (the class name), like ``dtype`` | |
275 | func : callable |
|
275 | func : callable | |
276 | The callable that will be called to compute the format data. The |
|
276 | The callable that will be called to compute the format data. The | |
277 | call signature of this function is simple, it must take the |
|
277 | call signature of this function is simple, it must take the | |
278 | object to be formatted and return the raw data for the given |
|
278 | object to be formatted and return the raw data for the given | |
279 | format. Subclasses may use a different call signature for the |
|
279 | format. Subclasses may use a different call signature for the | |
280 | `func` argument. |
|
280 | `func` argument. | |
281 | """ |
|
281 | """ | |
282 | key = (type_module, type_name) |
|
282 | key = (type_module, type_name) | |
283 | oldfunc = self.deferred_printers.get(key, None) |
|
283 | oldfunc = self.deferred_printers.get(key, None) | |
284 | if func is not None: |
|
284 | if func is not None: | |
285 | # To support easy restoration of old printers, we need to ignore |
|
285 | # To support easy restoration of old printers, we need to ignore | |
286 | # Nones. |
|
286 | # Nones. | |
287 | self.deferred_printers[key] = func |
|
287 | self.deferred_printers[key] = func | |
288 | return oldfunc |
|
288 | return oldfunc | |
289 |
|
289 | |||
290 | def _in_deferred_types(self, cls): |
|
290 | def _in_deferred_types(self, cls): | |
291 | """ |
|
291 | """ | |
292 | Check if the given class is specified in the deferred type registry. |
|
292 | Check if the given class is specified in the deferred type registry. | |
293 |
|
293 | |||
294 | Returns the printer from the registry if it exists, and None if the |
|
294 | Returns the printer from the registry if it exists, and None if the | |
295 | class is not in the registry. Successful matches will be moved to the |
|
295 | class is not in the registry. Successful matches will be moved to the | |
296 | regular type registry for future use. |
|
296 | regular type registry for future use. | |
297 | """ |
|
297 | """ | |
298 | mod = getattr(cls, '__module__', None) |
|
298 | mod = getattr(cls, '__module__', None) | |
299 | name = getattr(cls, '__name__', None) |
|
299 | name = getattr(cls, '__name__', None) | |
300 | key = (mod, name) |
|
300 | key = (mod, name) | |
301 | printer = None |
|
301 | printer = None | |
302 | if key in self.deferred_printers: |
|
302 | if key in self.deferred_printers: | |
303 | # Move the printer over to the regular registry. |
|
303 | # Move the printer over to the regular registry. | |
304 | printer = self.deferred_printers.pop(key) |
|
304 | printer = self.deferred_printers.pop(key) | |
305 | self.type_printers[cls] = printer |
|
305 | self.type_printers[cls] = printer | |
306 | return printer |
|
306 | return printer | |
307 |
|
307 | |||
308 |
|
308 | |||
309 | class PlainTextFormatter(BaseFormatter): |
|
309 | class PlainTextFormatter(BaseFormatter): | |
310 | """The default pretty-printer. |
|
310 | """The default pretty-printer. | |
311 |
|
311 | |||
312 | This uses :mod:`IPython.external.pretty` to compute the format data of |
|
312 | This uses :mod:`IPython.external.pretty` to compute the format data of | |
313 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
313 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
314 | See the documentation of :mod:`IPython.external.pretty` for details on |
|
314 | See the documentation of :mod:`IPython.external.pretty` for details on | |
315 | how to write pretty printers. Here is a simple example:: |
|
315 | how to write pretty printers. Here is a simple example:: | |
316 |
|
316 | |||
317 | def dtype_pprinter(obj, p, cycle): |
|
317 | def dtype_pprinter(obj, p, cycle): | |
318 | if cycle: |
|
318 | if cycle: | |
319 | return p.text('dtype(...)') |
|
319 | return p.text('dtype(...)') | |
320 | if hasattr(obj, 'fields'): |
|
320 | if hasattr(obj, 'fields'): | |
321 | if obj.fields is None: |
|
321 | if obj.fields is None: | |
322 | p.text(repr(obj)) |
|
322 | p.text(repr(obj)) | |
323 | else: |
|
323 | else: | |
324 | p.begin_group(7, 'dtype([') |
|
324 | p.begin_group(7, 'dtype([') | |
325 | for i, field in enumerate(obj.descr): |
|
325 | for i, field in enumerate(obj.descr): | |
326 | if i > 0: |
|
326 | if i > 0: | |
327 | p.text(',') |
|
327 | p.text(',') | |
328 | p.breakable() |
|
328 | p.breakable() | |
329 | p.pretty(field) |
|
329 | p.pretty(field) | |
330 | p.end_group(7, '])') |
|
330 | p.end_group(7, '])') | |
331 | """ |
|
331 | """ | |
332 |
|
332 | |||
333 | # The format type of data returned. |
|
333 | # The format type of data returned. | |
334 | format_type = Str('text/plain') |
|
334 | format_type = Str('text/plain') | |
335 |
|
335 | |||
336 | # This subclass ignores this attribute as it always need to return |
|
336 | # This subclass ignores this attribute as it always need to return | |
337 | # something. |
|
337 | # something. | |
338 | enabled = Bool(True, config=False) |
|
338 | enabled = Bool(True, config=False) | |
339 |
|
339 | |||
340 | # Look for a __pretty__ methods to use for pretty printing. |
|
340 | # Look for a __pretty__ methods to use for pretty printing. | |
341 | print_method = Str('__pretty__') |
|
341 | print_method = Str('__pretty__') | |
342 |
|
342 | |||
343 | # Whether to pretty-print or not. |
|
343 | # Whether to pretty-print or not. | |
344 | pprint = Bool(True, config=True) |
|
344 | pprint = Bool(True, config=True) | |
345 |
|
345 | |||
346 | # Whether to be verbose or not. |
|
346 | # Whether to be verbose or not. | |
347 | verbose = Bool(False, config=True) |
|
347 | verbose = Bool(False, config=True) | |
348 |
|
348 | |||
349 | # The maximum width. |
|
349 | # The maximum width. | |
350 | max_width = Int(79, config=True) |
|
350 | max_width = Int(79, config=True) | |
351 |
|
351 | |||
352 | # The newline character. |
|
352 | # The newline character. | |
353 | newline = Str('\n', config=True) |
|
353 | newline = Str('\n', config=True) | |
354 |
|
354 | |||
355 | # Use the default pretty printers from IPython.external.pretty. |
|
355 | # Use the default pretty printers from IPython.external.pretty. | |
356 | def _singleton_printers_default(self): |
|
356 | def _singleton_printers_default(self): | |
357 | return pretty._singleton_pprinters.copy() |
|
357 | return pretty._singleton_pprinters.copy() | |
358 |
|
358 | |||
359 | def _type_printers_default(self): |
|
359 | def _type_printers_default(self): | |
360 | return pretty._type_pprinters.copy() |
|
360 | return pretty._type_pprinters.copy() | |
361 |
|
361 | |||
362 | def _deferred_printers_default(self): |
|
362 | def _deferred_printers_default(self): | |
363 | return pretty._deferred_type_pprinters.copy() |
|
363 | return pretty._deferred_type_pprinters.copy() | |
364 |
|
364 | |||
365 | #### FormatterABC interface #### |
|
365 | #### FormatterABC interface #### | |
366 |
|
366 | |||
367 | def __call__(self, obj): |
|
367 | def __call__(self, obj): | |
368 | """Compute the pretty representation of the object.""" |
|
368 | """Compute the pretty representation of the object.""" | |
369 | if not self.pprint: |
|
369 | if not self.pprint: | |
370 | try: |
|
370 | try: | |
371 | return repr(obj) |
|
371 | return repr(obj) | |
372 | except TypeError: |
|
372 | except TypeError: | |
373 | return '' |
|
373 | return '' | |
374 | else: |
|
374 | else: | |
375 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
375 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
376 | stream = StringIO() |
|
376 | stream = StringIO() | |
377 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
377 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
378 | self.max_width, self.newline, |
|
378 | self.max_width, self.newline, | |
379 | singleton_pprinters=self.singleton_printers, |
|
379 | singleton_pprinters=self.singleton_printers, | |
380 | type_pprinters=self.type_printers, |
|
380 | type_pprinters=self.type_printers, | |
381 | deferred_pprinters=self.deferred_printers) |
|
381 | deferred_pprinters=self.deferred_printers) | |
382 | printer.pretty(obj) |
|
382 | printer.pretty(obj) | |
383 | printer.flush() |
|
383 | printer.flush() | |
384 | return stream.getvalue() |
|
384 | return stream.getvalue() | |
385 |
|
385 | |||
386 |
|
386 | |||
387 | class HTMLFormatter(BaseFormatter): |
|
387 | class HTMLFormatter(BaseFormatter): | |
388 | """An HTML formatter. |
|
388 | """An HTML formatter. | |
389 |
|
389 | |||
390 | To define the callables that compute the HTML representation of your |
|
390 | To define the callables that compute the HTML representation of your | |
391 | objects, define a :meth:`__html__` method or use the :meth:`for_type` |
|
391 | objects, define a :meth:`__html__` method or use the :meth:`for_type` | |
392 | or :meth:`for_type_by_name` methods to register functions that handle |
|
392 | or :meth:`for_type_by_name` methods to register functions that handle | |
393 | this. |
|
393 | this. | |
394 | """ |
|
394 | """ | |
395 | format_type = Str('text/html') |
|
395 | format_type = Str('text/html') | |
396 |
|
396 | |||
397 | print_method = Str('__html__') |
|
397 | print_method = Str('__html__') | |
398 |
|
398 | |||
399 |
|
399 | |||
400 | class SVGFormatter(BaseFormatter): |
|
400 | class SVGFormatter(BaseFormatter): | |
401 | """An SVG formatter. |
|
401 | """An SVG formatter. | |
402 |
|
402 | |||
403 | To define the callables that compute the SVG representation of your |
|
403 | To define the callables that compute the SVG representation of your | |
404 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` |
|
404 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
405 | or :meth:`for_type_by_name` methods to register functions that handle |
|
405 | or :meth:`for_type_by_name` methods to register functions that handle | |
406 | this. |
|
406 | this. | |
407 | """ |
|
407 | """ | |
408 | format_type = Str('image/svg+xml') |
|
408 | format_type = Str('image/svg+xml') | |
409 |
|
409 | |||
410 | print_method = Str('__svg__') |
|
410 | print_method = Str('__svg__') | |
411 |
|
411 | |||
412 |
|
412 | |||
413 | class PNGFormatter(BaseFormatter): |
|
413 | class PNGFormatter(BaseFormatter): | |
414 | """A PNG formatter. |
|
414 | """A PNG formatter. | |
415 |
|
415 | |||
416 | To define the callables that compute the PNG representation of your |
|
416 | To define the callables that compute the PNG representation of your | |
417 |
objects, define a :meth:`__ |
|
417 | objects, define a :meth:`__png__` method or use the :meth:`for_type` | |
418 | or :meth:`for_type_by_name` methods to register functions that handle |
|
418 | or :meth:`for_type_by_name` methods to register functions that handle | |
419 | this. The raw data should be the base64 encoded raw png data. |
|
419 | this. The raw data should be the base64 encoded raw png data. | |
420 | """ |
|
420 | """ | |
421 | format_type = Str('image/png') |
|
421 | format_type = Str('image/png') | |
422 |
|
422 | |||
423 | print_method = Str('__png__') |
|
423 | print_method = Str('__png__') | |
424 |
|
424 | |||
425 |
|
425 | |||
426 | class LatexFormatter(BaseFormatter): |
|
426 | class LatexFormatter(BaseFormatter): | |
427 | """A LaTeX formatter. |
|
427 | """A LaTeX formatter. | |
428 |
|
428 | |||
429 | To define the callables that compute the LaTeX representation of your |
|
429 | To define the callables that compute the LaTeX representation of your | |
430 | objects, define a :meth:`__latex__` method or use the :meth:`for_type` |
|
430 | objects, define a :meth:`__latex__` method or use the :meth:`for_type` | |
431 | or :meth:`for_type_by_name` methods to register functions that handle |
|
431 | or :meth:`for_type_by_name` methods to register functions that handle | |
432 | this. |
|
432 | this. | |
433 | """ |
|
433 | """ | |
434 | format_type = Str('text/latex') |
|
434 | format_type = Str('text/latex') | |
435 |
|
435 | |||
436 | print_method = Str('__latex__') |
|
436 | print_method = Str('__latex__') | |
437 |
|
437 | |||
438 |
|
438 | |||
439 | class JSONFormatter(BaseFormatter): |
|
439 | class JSONFormatter(BaseFormatter): | |
440 | """A JSON string formatter. |
|
440 | """A JSON string formatter. | |
441 |
|
441 | |||
442 | To define the callables that compute the JSON string representation of |
|
442 | To define the callables that compute the JSON string representation of | |
443 | your objects, define a :meth:`__json__` method or use the :meth:`for_type` |
|
443 | your objects, define a :meth:`__json__` method or use the :meth:`for_type` | |
444 | or :meth:`for_type_by_name` methods to register functions that handle |
|
444 | or :meth:`for_type_by_name` methods to register functions that handle | |
445 | this. |
|
445 | this. | |
446 | """ |
|
446 | """ | |
447 | format_type = Str('application/json') |
|
447 | format_type = Str('application/json') | |
448 |
|
448 | |||
449 | print_method = Str('__json__') |
|
449 | print_method = Str('__json__') | |
450 |
|
450 | |||
451 |
|
451 | |||
452 | FormatterABC.register(BaseFormatter) |
|
452 | FormatterABC.register(BaseFormatter) | |
453 | FormatterABC.register(PlainTextFormatter) |
|
453 | FormatterABC.register(PlainTextFormatter) | |
454 | FormatterABC.register(HTMLFormatter) |
|
454 | FormatterABC.register(HTMLFormatter) | |
455 | FormatterABC.register(SVGFormatter) |
|
455 | FormatterABC.register(SVGFormatter) | |
456 | FormatterABC.register(PNGFormatter) |
|
456 | FormatterABC.register(PNGFormatter) | |
457 | FormatterABC.register(LatexFormatter) |
|
457 | FormatterABC.register(LatexFormatter) | |
458 | FormatterABC.register(JSONFormatter) |
|
458 | FormatterABC.register(JSONFormatter) | |
459 |
|
459 | |||
460 |
|
460 | |||
461 | def format_display_data(obj, include=None, exclude=None): |
|
461 | def format_display_data(obj, include=None, exclude=None): | |
462 | """Return a format data dict for an object. |
|
462 | """Return a format data dict for an object. | |
463 |
|
463 | |||
464 | By default all format types will be computed. |
|
464 | By default all format types will be computed. | |
465 |
|
465 | |||
466 | The following MIME types are currently implemented: |
|
466 | The following MIME types are currently implemented: | |
467 |
|
467 | |||
468 | * text/plain |
|
468 | * text/plain | |
469 | * text/html |
|
469 | * text/html | |
470 | * text/latex |
|
470 | * text/latex | |
471 | * application/json |
|
471 | * application/json | |
472 | * image/png |
|
472 | * image/png | |
473 | * immage/svg+xml |
|
473 | * immage/svg+xml | |
474 |
|
474 | |||
475 | Parameters |
|
475 | Parameters | |
476 | ---------- |
|
476 | ---------- | |
477 | obj : object |
|
477 | obj : object | |
478 | The Python object whose format data will be computed. |
|
478 | The Python object whose format data will be computed. | |
479 |
|
479 | |||
480 | Returns |
|
480 | Returns | |
481 | ------- |
|
481 | ------- | |
482 | format_dict : dict |
|
482 | format_dict : dict | |
483 | A dictionary of key/value pairs, one or each format that was |
|
483 | A dictionary of key/value pairs, one or each format that was | |
484 | generated for the object. The keys are the format types, which |
|
484 | generated for the object. The keys are the format types, which | |
485 | will usually be MIME type strings and the values and JSON'able |
|
485 | will usually be MIME type strings and the values and JSON'able | |
486 | data structure containing the raw data for the representation in |
|
486 | data structure containing the raw data for the representation in | |
487 | that format. |
|
487 | that format. | |
488 | include : list or tuple, optional |
|
488 | include : list or tuple, optional | |
489 | A list of format type strings (MIME types) to include in the |
|
489 | A list of format type strings (MIME types) to include in the | |
490 | format data dict. If this is set *only* the format types included |
|
490 | format data dict. If this is set *only* the format types included | |
491 | in this list will be computed. |
|
491 | in this list will be computed. | |
492 | exclude : list or tuple, optional |
|
492 | exclude : list or tuple, optional | |
493 | A list of format type string (MIME types) to exclue in the format |
|
493 | A list of format type string (MIME types) to exclue in the format | |
494 | data dict. If this is set all format types will be computed, |
|
494 | data dict. If this is set all format types will be computed, | |
495 | except for those included in this argument. |
|
495 | except for those included in this argument. | |
496 | """ |
|
496 | """ | |
497 | from IPython.core.interactiveshell import InteractiveShell |
|
497 | from IPython.core.interactiveshell import InteractiveShell | |
498 |
|
498 | |||
499 | InteractiveShell.instance().display_formatter.format( |
|
499 | InteractiveShell.instance().display_formatter.format( | |
500 | obj, |
|
500 | obj, | |
501 | include, |
|
501 | include, | |
502 | exclude |
|
502 | exclude | |
503 | ) |
|
503 | ) |
General Comments 0
You need to be logged in to leave comments.
Login now