Show More
@@ -1,960 +1,945 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 | Inheritance diagram: |
|
4 | Inheritance diagram: | |
5 |
|
5 | |||
6 | .. inheritance-diagram:: IPython.core.formatters |
|
6 | .. inheritance-diagram:: IPython.core.formatters | |
7 | :parts: 3 |
|
7 | :parts: 3 | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | # Copyright (c) IPython Development Team. |
|
10 | # Copyright (c) IPython Development Team. | |
11 | # Distributed under the terms of the Modified BSD License. |
|
11 | # Distributed under the terms of the Modified BSD License. | |
12 |
|
12 | |||
13 | import abc |
|
13 | import abc | |
14 | import json |
|
14 | import json | |
15 | import sys |
|
15 | import sys | |
16 | import traceback |
|
16 | import traceback | |
17 | import warnings |
|
17 | import warnings | |
18 |
|
18 | |||
19 | from decorator import decorator |
|
19 | from decorator import decorator | |
20 |
|
20 | |||
21 | from traitlets.config.configurable import Configurable |
|
21 | from traitlets.config.configurable import Configurable | |
22 | from IPython.core.getipython import get_ipython |
|
22 | from IPython.core.getipython import get_ipython | |
23 | from IPython.utils.sentinel import Sentinel |
|
23 | from IPython.utils.sentinel import Sentinel | |
24 | from IPython.utils.dir2 import get_real_method |
|
24 | from IPython.utils.dir2 import get_real_method | |
25 | from IPython.lib import pretty |
|
25 | from IPython.lib import pretty | |
26 | from traitlets import ( |
|
26 | from traitlets import ( | |
27 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
27 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, | |
28 | ForwardDeclaredInstance, |
|
28 | ForwardDeclaredInstance, | |
29 | default, observe, |
|
29 | default, observe, | |
30 | ) |
|
30 | ) | |
31 | from IPython.utils.py3compat import ( |
|
31 | from IPython.utils.py3compat import ( | |
32 | with_metaclass, string_types, unicode_type, |
|
32 | with_metaclass, string_types, unicode_type, | |
33 | ) |
|
33 | ) | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | class DisplayFormatter(Configurable): |
|
36 | class DisplayFormatter(Configurable): | |
37 |
|
37 | |||
38 | # When set to true only the default plain text formatter will be used. |
|
|||
39 | plain_text_only = Bool(False).tag(config=True) |
|
|||
40 | def _plain_text_only_changed(self, name, old, new): |
|
|||
41 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
|||
42 |
|
||||
43 | It will be removed in IPython 5.0 |
|
|||
44 |
|
||||
45 | Use DisplayFormatter.active_types = ['text/plain'] |
|
|||
46 | for the same effect. |
|
|||
47 | """, DeprecationWarning) |
|
|||
48 | if new: |
|
|||
49 | self.active_types = ['text/plain'] |
|
|||
50 | else: |
|
|||
51 | self.active_types = self.format_types |
|
|||
52 |
|
||||
53 | active_types = List(Unicode(), |
|
38 | active_types = List(Unicode(), | |
54 | help="""List of currently active mime-types to display. |
|
39 | help="""List of currently active mime-types to display. | |
55 | You can use this to set a white-list for formats to display. |
|
40 | You can use this to set a white-list for formats to display. | |
56 |
|
41 | |||
57 | Most users will not need to change this value. |
|
42 | Most users will not need to change this value. | |
58 | """).tag(config=True) |
|
43 | """).tag(config=True) | |
59 |
|
44 | |||
60 | @default('active_types') |
|
45 | @default('active_types') | |
61 | def _active_types_default(self): |
|
46 | def _active_types_default(self): | |
62 | return self.format_types |
|
47 | return self.format_types | |
63 |
|
48 | |||
64 | @observe('active_types') |
|
49 | @observe('active_types') | |
65 | def _active_types_changed(self, change): |
|
50 | def _active_types_changed(self, change): | |
66 | for key, formatter in self.formatters.items(): |
|
51 | for key, formatter in self.formatters.items(): | |
67 | if key in change['new']: |
|
52 | if key in change['new']: | |
68 | formatter.enabled = True |
|
53 | formatter.enabled = True | |
69 | else: |
|
54 | else: | |
70 | formatter.enabled = False |
|
55 | formatter.enabled = False | |
71 |
|
56 | |||
72 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') |
|
57 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') | |
73 | @default('ipython_display_formatter') |
|
58 | @default('ipython_display_formatter') | |
74 | def _default_formatter(self): |
|
59 | def _default_formatter(self): | |
75 | return IPythonDisplayFormatter(parent=self) |
|
60 | return IPythonDisplayFormatter(parent=self) | |
76 |
|
61 | |||
77 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
62 | # A dict of formatter whose keys are format types (MIME types) and whose | |
78 | # values are subclasses of BaseFormatter. |
|
63 | # values are subclasses of BaseFormatter. | |
79 | formatters = Dict() |
|
64 | formatters = Dict() | |
80 | @default('formatters') |
|
65 | @default('formatters') | |
81 | def _formatters_default(self): |
|
66 | def _formatters_default(self): | |
82 | """Activate the default formatters.""" |
|
67 | """Activate the default formatters.""" | |
83 | formatter_classes = [ |
|
68 | formatter_classes = [ | |
84 | PlainTextFormatter, |
|
69 | PlainTextFormatter, | |
85 | HTMLFormatter, |
|
70 | HTMLFormatter, | |
86 | MarkdownFormatter, |
|
71 | MarkdownFormatter, | |
87 | SVGFormatter, |
|
72 | SVGFormatter, | |
88 | PNGFormatter, |
|
73 | PNGFormatter, | |
89 | PDFFormatter, |
|
74 | PDFFormatter, | |
90 | JPEGFormatter, |
|
75 | JPEGFormatter, | |
91 | LatexFormatter, |
|
76 | LatexFormatter, | |
92 | JSONFormatter, |
|
77 | JSONFormatter, | |
93 | JavascriptFormatter |
|
78 | JavascriptFormatter | |
94 | ] |
|
79 | ] | |
95 | d = {} |
|
80 | d = {} | |
96 | for cls in formatter_classes: |
|
81 | for cls in formatter_classes: | |
97 | f = cls(parent=self) |
|
82 | f = cls(parent=self) | |
98 | d[f.format_type] = f |
|
83 | d[f.format_type] = f | |
99 | return d |
|
84 | return d | |
100 |
|
85 | |||
101 | def format(self, obj, include=None, exclude=None): |
|
86 | def format(self, obj, include=None, exclude=None): | |
102 | """Return a format data dict for an object. |
|
87 | """Return a format data dict for an object. | |
103 |
|
88 | |||
104 | By default all format types will be computed. |
|
89 | By default all format types will be computed. | |
105 |
|
90 | |||
106 | The following MIME types are currently implemented: |
|
91 | The following MIME types are currently implemented: | |
107 |
|
92 | |||
108 | * text/plain |
|
93 | * text/plain | |
109 | * text/html |
|
94 | * text/html | |
110 | * text/markdown |
|
95 | * text/markdown | |
111 | * text/latex |
|
96 | * text/latex | |
112 | * application/json |
|
97 | * application/json | |
113 | * application/javascript |
|
98 | * application/javascript | |
114 | * application/pdf |
|
99 | * application/pdf | |
115 | * image/png |
|
100 | * image/png | |
116 | * image/jpeg |
|
101 | * image/jpeg | |
117 | * image/svg+xml |
|
102 | * image/svg+xml | |
118 |
|
103 | |||
119 | Parameters |
|
104 | Parameters | |
120 | ---------- |
|
105 | ---------- | |
121 | obj : object |
|
106 | obj : object | |
122 | The Python object whose format data will be computed. |
|
107 | The Python object whose format data will be computed. | |
123 | include : list or tuple, optional |
|
108 | include : list or tuple, optional | |
124 | A list of format type strings (MIME types) to include in the |
|
109 | A list of format type strings (MIME types) to include in the | |
125 | format data dict. If this is set *only* the format types included |
|
110 | format data dict. If this is set *only* the format types included | |
126 | in this list will be computed. |
|
111 | in this list will be computed. | |
127 | exclude : list or tuple, optional |
|
112 | exclude : list or tuple, optional | |
128 | A list of format type string (MIME types) to exclude in the format |
|
113 | A list of format type string (MIME types) to exclude in the format | |
129 | data dict. If this is set all format types will be computed, |
|
114 | data dict. If this is set all format types will be computed, | |
130 | except for those included in this argument. |
|
115 | except for those included in this argument. | |
131 |
|
116 | |||
132 | Returns |
|
117 | Returns | |
133 | ------- |
|
118 | ------- | |
134 | (format_dict, metadata_dict) : tuple of two dicts |
|
119 | (format_dict, metadata_dict) : tuple of two dicts | |
135 |
|
120 | |||
136 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
121 | format_dict is a dictionary of key/value pairs, one of each format that was | |
137 | generated for the object. The keys are the format types, which |
|
122 | generated for the object. The keys are the format types, which | |
138 | will usually be MIME type strings and the values and JSON'able |
|
123 | will usually be MIME type strings and the values and JSON'able | |
139 | data structure containing the raw data for the representation in |
|
124 | data structure containing the raw data for the representation in | |
140 | that format. |
|
125 | that format. | |
141 |
|
126 | |||
142 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
127 | metadata_dict is a dictionary of metadata about each mime-type output. | |
143 | Its keys will be a strict subset of the keys in format_dict. |
|
128 | Its keys will be a strict subset of the keys in format_dict. | |
144 | """ |
|
129 | """ | |
145 | format_dict = {} |
|
130 | format_dict = {} | |
146 | md_dict = {} |
|
131 | md_dict = {} | |
147 |
|
132 | |||
148 | if self.ipython_display_formatter(obj): |
|
133 | if self.ipython_display_formatter(obj): | |
149 | # object handled itself, don't proceed |
|
134 | # object handled itself, don't proceed | |
150 | return {}, {} |
|
135 | return {}, {} | |
151 |
|
136 | |||
152 | for format_type, formatter in self.formatters.items(): |
|
137 | for format_type, formatter in self.formatters.items(): | |
153 | if include and format_type not in include: |
|
138 | if include and format_type not in include: | |
154 | continue |
|
139 | continue | |
155 | if exclude and format_type in exclude: |
|
140 | if exclude and format_type in exclude: | |
156 | continue |
|
141 | continue | |
157 |
|
142 | |||
158 | md = None |
|
143 | md = None | |
159 | try: |
|
144 | try: | |
160 | data = formatter(obj) |
|
145 | data = formatter(obj) | |
161 | except: |
|
146 | except: | |
162 | # FIXME: log the exception |
|
147 | # FIXME: log the exception | |
163 | raise |
|
148 | raise | |
164 |
|
149 | |||
165 | # formatters can return raw data or (data, metadata) |
|
150 | # formatters can return raw data or (data, metadata) | |
166 | if isinstance(data, tuple) and len(data) == 2: |
|
151 | if isinstance(data, tuple) and len(data) == 2: | |
167 | data, md = data |
|
152 | data, md = data | |
168 |
|
153 | |||
169 | if data is not None: |
|
154 | if data is not None: | |
170 | format_dict[format_type] = data |
|
155 | format_dict[format_type] = data | |
171 | if md is not None: |
|
156 | if md is not None: | |
172 | md_dict[format_type] = md |
|
157 | md_dict[format_type] = md | |
173 |
|
158 | |||
174 | return format_dict, md_dict |
|
159 | return format_dict, md_dict | |
175 |
|
160 | |||
176 | @property |
|
161 | @property | |
177 | def format_types(self): |
|
162 | def format_types(self): | |
178 | """Return the format types (MIME types) of the active formatters.""" |
|
163 | """Return the format types (MIME types) of the active formatters.""" | |
179 | return list(self.formatters.keys()) |
|
164 | return list(self.formatters.keys()) | |
180 |
|
165 | |||
181 |
|
166 | |||
182 | #----------------------------------------------------------------------------- |
|
167 | #----------------------------------------------------------------------------- | |
183 | # Formatters for specific format types (text, html, svg, etc.) |
|
168 | # Formatters for specific format types (text, html, svg, etc.) | |
184 | #----------------------------------------------------------------------------- |
|
169 | #----------------------------------------------------------------------------- | |
185 |
|
170 | |||
186 |
|
171 | |||
187 | def _safe_repr(obj): |
|
172 | def _safe_repr(obj): | |
188 | """Try to return a repr of an object |
|
173 | """Try to return a repr of an object | |
189 |
|
174 | |||
190 | always returns a string, at least. |
|
175 | always returns a string, at least. | |
191 | """ |
|
176 | """ | |
192 | try: |
|
177 | try: | |
193 | return repr(obj) |
|
178 | return repr(obj) | |
194 | except Exception as e: |
|
179 | except Exception as e: | |
195 | return "un-repr-able object (%r)" % e |
|
180 | return "un-repr-able object (%r)" % e | |
196 |
|
181 | |||
197 |
|
182 | |||
198 | class FormatterWarning(UserWarning): |
|
183 | class FormatterWarning(UserWarning): | |
199 | """Warning class for errors in formatters""" |
|
184 | """Warning class for errors in formatters""" | |
200 |
|
185 | |||
201 | @decorator |
|
186 | @decorator | |
202 | def catch_format_error(method, self, *args, **kwargs): |
|
187 | def catch_format_error(method, self, *args, **kwargs): | |
203 | """show traceback on failed format call""" |
|
188 | """show traceback on failed format call""" | |
204 | try: |
|
189 | try: | |
205 | r = method(self, *args, **kwargs) |
|
190 | r = method(self, *args, **kwargs) | |
206 | except NotImplementedError: |
|
191 | except NotImplementedError: | |
207 | # don't warn on NotImplementedErrors |
|
192 | # don't warn on NotImplementedErrors | |
208 | return None |
|
193 | return None | |
209 | except Exception: |
|
194 | except Exception: | |
210 | exc_info = sys.exc_info() |
|
195 | exc_info = sys.exc_info() | |
211 | ip = get_ipython() |
|
196 | ip = get_ipython() | |
212 | if ip is not None: |
|
197 | if ip is not None: | |
213 | ip.showtraceback(exc_info) |
|
198 | ip.showtraceback(exc_info) | |
214 | else: |
|
199 | else: | |
215 | traceback.print_exception(*exc_info) |
|
200 | traceback.print_exception(*exc_info) | |
216 | return None |
|
201 | return None | |
217 | return self._check_return(r, args[0]) |
|
202 | return self._check_return(r, args[0]) | |
218 |
|
203 | |||
219 |
|
204 | |||
220 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
205 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): | |
221 | """ Abstract base class for Formatters. |
|
206 | """ Abstract base class for Formatters. | |
222 |
|
207 | |||
223 | A formatter is a callable class that is responsible for computing the |
|
208 | A formatter is a callable class that is responsible for computing the | |
224 | raw format data for a particular format type (MIME type). For example, |
|
209 | raw format data for a particular format type (MIME type). For example, | |
225 | an HTML formatter would have a format type of `text/html` and would return |
|
210 | an HTML formatter would have a format type of `text/html` and would return | |
226 | the HTML representation of the object when called. |
|
211 | the HTML representation of the object when called. | |
227 | """ |
|
212 | """ | |
228 |
|
213 | |||
229 | # The format type of the data returned, usually a MIME type. |
|
214 | # The format type of the data returned, usually a MIME type. | |
230 | format_type = 'text/plain' |
|
215 | format_type = 'text/plain' | |
231 |
|
216 | |||
232 | # Is the formatter enabled... |
|
217 | # Is the formatter enabled... | |
233 | enabled = True |
|
218 | enabled = True | |
234 |
|
219 | |||
235 | @abc.abstractmethod |
|
220 | @abc.abstractmethod | |
236 | def __call__(self, obj): |
|
221 | def __call__(self, obj): | |
237 | """Return a JSON'able representation of the object. |
|
222 | """Return a JSON'able representation of the object. | |
238 |
|
223 | |||
239 | If the object cannot be formatted by this formatter, |
|
224 | If the object cannot be formatted by this formatter, | |
240 | warn and return None. |
|
225 | warn and return None. | |
241 | """ |
|
226 | """ | |
242 | return repr(obj) |
|
227 | return repr(obj) | |
243 |
|
228 | |||
244 |
|
229 | |||
245 | def _mod_name_key(typ): |
|
230 | def _mod_name_key(typ): | |
246 | """Return a (__module__, __name__) tuple for a type. |
|
231 | """Return a (__module__, __name__) tuple for a type. | |
247 |
|
232 | |||
248 | Used as key in Formatter.deferred_printers. |
|
233 | Used as key in Formatter.deferred_printers. | |
249 | """ |
|
234 | """ | |
250 | module = getattr(typ, '__module__', None) |
|
235 | module = getattr(typ, '__module__', None) | |
251 | name = getattr(typ, '__name__', None) |
|
236 | name = getattr(typ, '__name__', None) | |
252 | return (module, name) |
|
237 | return (module, name) | |
253 |
|
238 | |||
254 |
|
239 | |||
255 | def _get_type(obj): |
|
240 | def _get_type(obj): | |
256 | """Return the type of an instance (old and new-style)""" |
|
241 | """Return the type of an instance (old and new-style)""" | |
257 | return getattr(obj, '__class__', None) or type(obj) |
|
242 | return getattr(obj, '__class__', None) or type(obj) | |
258 |
|
243 | |||
259 |
|
244 | |||
260 | _raise_key_error = Sentinel('_raise_key_error', __name__, |
|
245 | _raise_key_error = Sentinel('_raise_key_error', __name__, | |
261 | """ |
|
246 | """ | |
262 | Special value to raise a KeyError |
|
247 | Special value to raise a KeyError | |
263 |
|
248 | |||
264 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` |
|
249 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` | |
265 | """) |
|
250 | """) | |
266 |
|
251 | |||
267 |
|
252 | |||
268 | class BaseFormatter(Configurable): |
|
253 | class BaseFormatter(Configurable): | |
269 | """A base formatter class that is configurable. |
|
254 | """A base formatter class that is configurable. | |
270 |
|
255 | |||
271 | This formatter should usually be used as the base class of all formatters. |
|
256 | This formatter should usually be used as the base class of all formatters. | |
272 | It is a traited :class:`Configurable` class and includes an extensible |
|
257 | It is a traited :class:`Configurable` class and includes an extensible | |
273 | API for users to determine how their objects are formatted. The following |
|
258 | API for users to determine how their objects are formatted. The following | |
274 | logic is used to find a function to format an given object. |
|
259 | logic is used to find a function to format an given object. | |
275 |
|
260 | |||
276 | 1. The object is introspected to see if it has a method with the name |
|
261 | 1. The object is introspected to see if it has a method with the name | |
277 | :attr:`print_method`. If is does, that object is passed to that method |
|
262 | :attr:`print_method`. If is does, that object is passed to that method | |
278 | for formatting. |
|
263 | for formatting. | |
279 | 2. If no print method is found, three internal dictionaries are consulted |
|
264 | 2. If no print method is found, three internal dictionaries are consulted | |
280 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
265 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
281 | and :attr:`deferred_printers`. |
|
266 | and :attr:`deferred_printers`. | |
282 |
|
267 | |||
283 | Users should use these dictionaries to register functions that will be |
|
268 | Users should use these dictionaries to register functions that will be | |
284 | used to compute the format data for their objects (if those objects don't |
|
269 | used to compute the format data for their objects (if those objects don't | |
285 | have the special print methods). The easiest way of using these |
|
270 | have the special print methods). The easiest way of using these | |
286 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
271 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
287 | methods. |
|
272 | methods. | |
288 |
|
273 | |||
289 | If no function/callable is found to compute the format data, ``None`` is |
|
274 | If no function/callable is found to compute the format data, ``None`` is | |
290 | returned and this format type is not used. |
|
275 | returned and this format type is not used. | |
291 | """ |
|
276 | """ | |
292 |
|
277 | |||
293 | format_type = Unicode('text/plain') |
|
278 | format_type = Unicode('text/plain') | |
294 | _return_type = string_types |
|
279 | _return_type = string_types | |
295 |
|
280 | |||
296 | enabled = Bool(True).tag(config=True) |
|
281 | enabled = Bool(True).tag(config=True) | |
297 |
|
282 | |||
298 | print_method = ObjectName('__repr__') |
|
283 | print_method = ObjectName('__repr__') | |
299 |
|
284 | |||
300 | # The singleton printers. |
|
285 | # The singleton printers. | |
301 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
286 | # Maps the IDs of the builtin singleton objects to the format functions. | |
302 | singleton_printers = Dict().tag(config=True) |
|
287 | singleton_printers = Dict().tag(config=True) | |
303 |
|
288 | |||
304 | # The type-specific printers. |
|
289 | # The type-specific printers. | |
305 | # Map type objects to the format functions. |
|
290 | # Map type objects to the format functions. | |
306 | type_printers = Dict().tag(config=True) |
|
291 | type_printers = Dict().tag(config=True) | |
307 |
|
292 | |||
308 | # The deferred-import type-specific printers. |
|
293 | # The deferred-import type-specific printers. | |
309 | # Map (modulename, classname) pairs to the format functions. |
|
294 | # Map (modulename, classname) pairs to the format functions. | |
310 | deferred_printers = Dict().tag(config=True) |
|
295 | deferred_printers = Dict().tag(config=True) | |
311 |
|
296 | |||
312 | @catch_format_error |
|
297 | @catch_format_error | |
313 | def __call__(self, obj): |
|
298 | def __call__(self, obj): | |
314 | """Compute the format for an object.""" |
|
299 | """Compute the format for an object.""" | |
315 | if self.enabled: |
|
300 | if self.enabled: | |
316 | # lookup registered printer |
|
301 | # lookup registered printer | |
317 | try: |
|
302 | try: | |
318 | printer = self.lookup(obj) |
|
303 | printer = self.lookup(obj) | |
319 | except KeyError: |
|
304 | except KeyError: | |
320 | pass |
|
305 | pass | |
321 | else: |
|
306 | else: | |
322 | return printer(obj) |
|
307 | return printer(obj) | |
323 | # Finally look for special method names |
|
308 | # Finally look for special method names | |
324 | method = get_real_method(obj, self.print_method) |
|
309 | method = get_real_method(obj, self.print_method) | |
325 | if method is not None: |
|
310 | if method is not None: | |
326 | return method() |
|
311 | return method() | |
327 | return None |
|
312 | return None | |
328 | else: |
|
313 | else: | |
329 | return None |
|
314 | return None | |
330 |
|
315 | |||
331 | def __contains__(self, typ): |
|
316 | def __contains__(self, typ): | |
332 | """map in to lookup_by_type""" |
|
317 | """map in to lookup_by_type""" | |
333 | try: |
|
318 | try: | |
334 | self.lookup_by_type(typ) |
|
319 | self.lookup_by_type(typ) | |
335 | except KeyError: |
|
320 | except KeyError: | |
336 | return False |
|
321 | return False | |
337 | else: |
|
322 | else: | |
338 | return True |
|
323 | return True | |
339 |
|
324 | |||
340 | def _check_return(self, r, obj): |
|
325 | def _check_return(self, r, obj): | |
341 | """Check that a return value is appropriate |
|
326 | """Check that a return value is appropriate | |
342 |
|
327 | |||
343 | Return the value if so, None otherwise, warning if invalid. |
|
328 | Return the value if so, None otherwise, warning if invalid. | |
344 | """ |
|
329 | """ | |
345 | if r is None or isinstance(r, self._return_type) or \ |
|
330 | if r is None or isinstance(r, self._return_type) or \ | |
346 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
331 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): | |
347 | return r |
|
332 | return r | |
348 | else: |
|
333 | else: | |
349 | warnings.warn( |
|
334 | warnings.warn( | |
350 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
335 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ | |
351 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), |
|
336 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), | |
352 | FormatterWarning |
|
337 | FormatterWarning | |
353 | ) |
|
338 | ) | |
354 |
|
339 | |||
355 | def lookup(self, obj): |
|
340 | def lookup(self, obj): | |
356 | """Look up the formatter for a given instance. |
|
341 | """Look up the formatter for a given instance. | |
357 |
|
342 | |||
358 | Parameters |
|
343 | Parameters | |
359 | ---------- |
|
344 | ---------- | |
360 | obj : object instance |
|
345 | obj : object instance | |
361 |
|
346 | |||
362 | Returns |
|
347 | Returns | |
363 | ------- |
|
348 | ------- | |
364 | f : callable |
|
349 | f : callable | |
365 | The registered formatting callable for the type. |
|
350 | The registered formatting callable for the type. | |
366 |
|
351 | |||
367 | Raises |
|
352 | Raises | |
368 | ------ |
|
353 | ------ | |
369 | KeyError if the type has not been registered. |
|
354 | KeyError if the type has not been registered. | |
370 | """ |
|
355 | """ | |
371 | # look for singleton first |
|
356 | # look for singleton first | |
372 | obj_id = id(obj) |
|
357 | obj_id = id(obj) | |
373 | if obj_id in self.singleton_printers: |
|
358 | if obj_id in self.singleton_printers: | |
374 | return self.singleton_printers[obj_id] |
|
359 | return self.singleton_printers[obj_id] | |
375 | # then lookup by type |
|
360 | # then lookup by type | |
376 | return self.lookup_by_type(_get_type(obj)) |
|
361 | return self.lookup_by_type(_get_type(obj)) | |
377 |
|
362 | |||
378 | def lookup_by_type(self, typ): |
|
363 | def lookup_by_type(self, typ): | |
379 | """Look up the registered formatter for a type. |
|
364 | """Look up the registered formatter for a type. | |
380 |
|
365 | |||
381 | Parameters |
|
366 | Parameters | |
382 | ---------- |
|
367 | ---------- | |
383 | typ : type or '__module__.__name__' string for a type |
|
368 | typ : type or '__module__.__name__' string for a type | |
384 |
|
369 | |||
385 | Returns |
|
370 | Returns | |
386 | ------- |
|
371 | ------- | |
387 | f : callable |
|
372 | f : callable | |
388 | The registered formatting callable for the type. |
|
373 | The registered formatting callable for the type. | |
389 |
|
374 | |||
390 | Raises |
|
375 | Raises | |
391 | ------ |
|
376 | ------ | |
392 | KeyError if the type has not been registered. |
|
377 | KeyError if the type has not been registered. | |
393 | """ |
|
378 | """ | |
394 | if isinstance(typ, string_types): |
|
379 | if isinstance(typ, string_types): | |
395 | typ_key = tuple(typ.rsplit('.',1)) |
|
380 | typ_key = tuple(typ.rsplit('.',1)) | |
396 | if typ_key not in self.deferred_printers: |
|
381 | if typ_key not in self.deferred_printers: | |
397 | # We may have it cached in the type map. We will have to |
|
382 | # We may have it cached in the type map. We will have to | |
398 | # iterate over all of the types to check. |
|
383 | # iterate over all of the types to check. | |
399 | for cls in self.type_printers: |
|
384 | for cls in self.type_printers: | |
400 | if _mod_name_key(cls) == typ_key: |
|
385 | if _mod_name_key(cls) == typ_key: | |
401 | return self.type_printers[cls] |
|
386 | return self.type_printers[cls] | |
402 | else: |
|
387 | else: | |
403 | return self.deferred_printers[typ_key] |
|
388 | return self.deferred_printers[typ_key] | |
404 | else: |
|
389 | else: | |
405 | for cls in pretty._get_mro(typ): |
|
390 | for cls in pretty._get_mro(typ): | |
406 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
391 | if cls in self.type_printers or self._in_deferred_types(cls): | |
407 | return self.type_printers[cls] |
|
392 | return self.type_printers[cls] | |
408 |
|
393 | |||
409 | # If we have reached here, the lookup failed. |
|
394 | # If we have reached here, the lookup failed. | |
410 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
395 | raise KeyError("No registered printer for {0!r}".format(typ)) | |
411 |
|
396 | |||
412 | def for_type(self, typ, func=None): |
|
397 | def for_type(self, typ, func=None): | |
413 | """Add a format function for a given type. |
|
398 | """Add a format function for a given type. | |
414 |
|
399 | |||
415 | Parameters |
|
400 | Parameters | |
416 | ----------- |
|
401 | ----------- | |
417 | typ : type or '__module__.__name__' string for a type |
|
402 | typ : type or '__module__.__name__' string for a type | |
418 | The class of the object that will be formatted using `func`. |
|
403 | The class of the object that will be formatted using `func`. | |
419 | func : callable |
|
404 | func : callable | |
420 | A callable for computing the format data. |
|
405 | A callable for computing the format data. | |
421 | `func` will be called with the object to be formatted, |
|
406 | `func` will be called with the object to be formatted, | |
422 | and will return the raw data in this formatter's format. |
|
407 | and will return the raw data in this formatter's format. | |
423 | Subclasses may use a different call signature for the |
|
408 | Subclasses may use a different call signature for the | |
424 | `func` argument. |
|
409 | `func` argument. | |
425 |
|
410 | |||
426 | If `func` is None or not specified, there will be no change, |
|
411 | If `func` is None or not specified, there will be no change, | |
427 | only returning the current value. |
|
412 | only returning the current value. | |
428 |
|
413 | |||
429 | Returns |
|
414 | Returns | |
430 | ------- |
|
415 | ------- | |
431 | oldfunc : callable |
|
416 | oldfunc : callable | |
432 | The currently registered callable. |
|
417 | The currently registered callable. | |
433 | If you are registering a new formatter, |
|
418 | If you are registering a new formatter, | |
434 | this will be the previous value (to enable restoring later). |
|
419 | this will be the previous value (to enable restoring later). | |
435 | """ |
|
420 | """ | |
436 | # if string given, interpret as 'pkg.module.class_name' |
|
421 | # if string given, interpret as 'pkg.module.class_name' | |
437 | if isinstance(typ, string_types): |
|
422 | if isinstance(typ, string_types): | |
438 | type_module, type_name = typ.rsplit('.', 1) |
|
423 | type_module, type_name = typ.rsplit('.', 1) | |
439 | return self.for_type_by_name(type_module, type_name, func) |
|
424 | return self.for_type_by_name(type_module, type_name, func) | |
440 |
|
425 | |||
441 | try: |
|
426 | try: | |
442 | oldfunc = self.lookup_by_type(typ) |
|
427 | oldfunc = self.lookup_by_type(typ) | |
443 | except KeyError: |
|
428 | except KeyError: | |
444 | oldfunc = None |
|
429 | oldfunc = None | |
445 |
|
430 | |||
446 | if func is not None: |
|
431 | if func is not None: | |
447 | self.type_printers[typ] = func |
|
432 | self.type_printers[typ] = func | |
448 |
|
433 | |||
449 | return oldfunc |
|
434 | return oldfunc | |
450 |
|
435 | |||
451 | def for_type_by_name(self, type_module, type_name, func=None): |
|
436 | def for_type_by_name(self, type_module, type_name, func=None): | |
452 | """Add a format function for a type specified by the full dotted |
|
437 | """Add a format function for a type specified by the full dotted | |
453 | module and name of the type, rather than the type of the object. |
|
438 | module and name of the type, rather than the type of the object. | |
454 |
|
439 | |||
455 | Parameters |
|
440 | Parameters | |
456 | ---------- |
|
441 | ---------- | |
457 | type_module : str |
|
442 | type_module : str | |
458 | The full dotted name of the module the type is defined in, like |
|
443 | The full dotted name of the module the type is defined in, like | |
459 | ``numpy``. |
|
444 | ``numpy``. | |
460 | type_name : str |
|
445 | type_name : str | |
461 | The name of the type (the class name), like ``dtype`` |
|
446 | The name of the type (the class name), like ``dtype`` | |
462 | func : callable |
|
447 | func : callable | |
463 | A callable for computing the format data. |
|
448 | A callable for computing the format data. | |
464 | `func` will be called with the object to be formatted, |
|
449 | `func` will be called with the object to be formatted, | |
465 | and will return the raw data in this formatter's format. |
|
450 | and will return the raw data in this formatter's format. | |
466 | Subclasses may use a different call signature for the |
|
451 | Subclasses may use a different call signature for the | |
467 | `func` argument. |
|
452 | `func` argument. | |
468 |
|
453 | |||
469 | If `func` is None or unspecified, there will be no change, |
|
454 | If `func` is None or unspecified, there will be no change, | |
470 | only returning the current value. |
|
455 | only returning the current value. | |
471 |
|
456 | |||
472 | Returns |
|
457 | Returns | |
473 | ------- |
|
458 | ------- | |
474 | oldfunc : callable |
|
459 | oldfunc : callable | |
475 | The currently registered callable. |
|
460 | The currently registered callable. | |
476 | If you are registering a new formatter, |
|
461 | If you are registering a new formatter, | |
477 | this will be the previous value (to enable restoring later). |
|
462 | this will be the previous value (to enable restoring later). | |
478 | """ |
|
463 | """ | |
479 | key = (type_module, type_name) |
|
464 | key = (type_module, type_name) | |
480 |
|
465 | |||
481 | try: |
|
466 | try: | |
482 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
467 | oldfunc = self.lookup_by_type("%s.%s" % key) | |
483 | except KeyError: |
|
468 | except KeyError: | |
484 | oldfunc = None |
|
469 | oldfunc = None | |
485 |
|
470 | |||
486 | if func is not None: |
|
471 | if func is not None: | |
487 | self.deferred_printers[key] = func |
|
472 | self.deferred_printers[key] = func | |
488 | return oldfunc |
|
473 | return oldfunc | |
489 |
|
474 | |||
490 | def pop(self, typ, default=_raise_key_error): |
|
475 | def pop(self, typ, default=_raise_key_error): | |
491 | """Pop a formatter for the given type. |
|
476 | """Pop a formatter for the given type. | |
492 |
|
477 | |||
493 | Parameters |
|
478 | Parameters | |
494 | ---------- |
|
479 | ---------- | |
495 | typ : type or '__module__.__name__' string for a type |
|
480 | typ : type or '__module__.__name__' string for a type | |
496 | default : object |
|
481 | default : object | |
497 | value to be returned if no formatter is registered for typ. |
|
482 | value to be returned if no formatter is registered for typ. | |
498 |
|
483 | |||
499 | Returns |
|
484 | Returns | |
500 | ------- |
|
485 | ------- | |
501 | obj : object |
|
486 | obj : object | |
502 | The last registered object for the type. |
|
487 | The last registered object for the type. | |
503 |
|
488 | |||
504 | Raises |
|
489 | Raises | |
505 | ------ |
|
490 | ------ | |
506 | KeyError if the type is not registered and default is not specified. |
|
491 | KeyError if the type is not registered and default is not specified. | |
507 | """ |
|
492 | """ | |
508 |
|
493 | |||
509 | if isinstance(typ, string_types): |
|
494 | if isinstance(typ, string_types): | |
510 | typ_key = tuple(typ.rsplit('.',1)) |
|
495 | typ_key = tuple(typ.rsplit('.',1)) | |
511 | if typ_key not in self.deferred_printers: |
|
496 | if typ_key not in self.deferred_printers: | |
512 | # We may have it cached in the type map. We will have to |
|
497 | # We may have it cached in the type map. We will have to | |
513 | # iterate over all of the types to check. |
|
498 | # iterate over all of the types to check. | |
514 | for cls in self.type_printers: |
|
499 | for cls in self.type_printers: | |
515 | if _mod_name_key(cls) == typ_key: |
|
500 | if _mod_name_key(cls) == typ_key: | |
516 | old = self.type_printers.pop(cls) |
|
501 | old = self.type_printers.pop(cls) | |
517 | break |
|
502 | break | |
518 | else: |
|
503 | else: | |
519 | old = default |
|
504 | old = default | |
520 | else: |
|
505 | else: | |
521 | old = self.deferred_printers.pop(typ_key) |
|
506 | old = self.deferred_printers.pop(typ_key) | |
522 | else: |
|
507 | else: | |
523 | if typ in self.type_printers: |
|
508 | if typ in self.type_printers: | |
524 | old = self.type_printers.pop(typ) |
|
509 | old = self.type_printers.pop(typ) | |
525 | else: |
|
510 | else: | |
526 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
511 | old = self.deferred_printers.pop(_mod_name_key(typ), default) | |
527 | if old is _raise_key_error: |
|
512 | if old is _raise_key_error: | |
528 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
513 | raise KeyError("No registered value for {0!r}".format(typ)) | |
529 | return old |
|
514 | return old | |
530 |
|
515 | |||
531 | def _in_deferred_types(self, cls): |
|
516 | def _in_deferred_types(self, cls): | |
532 | """ |
|
517 | """ | |
533 | Check if the given class is specified in the deferred type registry. |
|
518 | Check if the given class is specified in the deferred type registry. | |
534 |
|
519 | |||
535 | Successful matches will be moved to the regular type registry for future use. |
|
520 | Successful matches will be moved to the regular type registry for future use. | |
536 | """ |
|
521 | """ | |
537 | mod = getattr(cls, '__module__', None) |
|
522 | mod = getattr(cls, '__module__', None) | |
538 | name = getattr(cls, '__name__', None) |
|
523 | name = getattr(cls, '__name__', None) | |
539 | key = (mod, name) |
|
524 | key = (mod, name) | |
540 | if key in self.deferred_printers: |
|
525 | if key in self.deferred_printers: | |
541 | # Move the printer over to the regular registry. |
|
526 | # Move the printer over to the regular registry. | |
542 | printer = self.deferred_printers.pop(key) |
|
527 | printer = self.deferred_printers.pop(key) | |
543 | self.type_printers[cls] = printer |
|
528 | self.type_printers[cls] = printer | |
544 | return True |
|
529 | return True | |
545 | return False |
|
530 | return False | |
546 |
|
531 | |||
547 |
|
532 | |||
548 | class PlainTextFormatter(BaseFormatter): |
|
533 | class PlainTextFormatter(BaseFormatter): | |
549 | """The default pretty-printer. |
|
534 | """The default pretty-printer. | |
550 |
|
535 | |||
551 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
536 | This uses :mod:`IPython.lib.pretty` to compute the format data of | |
552 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
537 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
553 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
538 | See the documentation of :mod:`IPython.lib.pretty` for details on | |
554 | how to write pretty printers. Here is a simple example:: |
|
539 | how to write pretty printers. Here is a simple example:: | |
555 |
|
540 | |||
556 | def dtype_pprinter(obj, p, cycle): |
|
541 | def dtype_pprinter(obj, p, cycle): | |
557 | if cycle: |
|
542 | if cycle: | |
558 | return p.text('dtype(...)') |
|
543 | return p.text('dtype(...)') | |
559 | if hasattr(obj, 'fields'): |
|
544 | if hasattr(obj, 'fields'): | |
560 | if obj.fields is None: |
|
545 | if obj.fields is None: | |
561 | p.text(repr(obj)) |
|
546 | p.text(repr(obj)) | |
562 | else: |
|
547 | else: | |
563 | p.begin_group(7, 'dtype([') |
|
548 | p.begin_group(7, 'dtype([') | |
564 | for i, field in enumerate(obj.descr): |
|
549 | for i, field in enumerate(obj.descr): | |
565 | if i > 0: |
|
550 | if i > 0: | |
566 | p.text(',') |
|
551 | p.text(',') | |
567 | p.breakable() |
|
552 | p.breakable() | |
568 | p.pretty(field) |
|
553 | p.pretty(field) | |
569 | p.end_group(7, '])') |
|
554 | p.end_group(7, '])') | |
570 | """ |
|
555 | """ | |
571 |
|
556 | |||
572 | # The format type of data returned. |
|
557 | # The format type of data returned. | |
573 | format_type = Unicode('text/plain') |
|
558 | format_type = Unicode('text/plain') | |
574 |
|
559 | |||
575 | # This subclass ignores this attribute as it always need to return |
|
560 | # This subclass ignores this attribute as it always need to return | |
576 | # something. |
|
561 | # something. | |
577 | enabled = Bool(True).tag(config=False) |
|
562 | enabled = Bool(True).tag(config=False) | |
578 |
|
563 | |||
579 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, |
|
564 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, | |
580 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. |
|
565 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. | |
581 |
|
566 | |||
582 | Set to 0 to disable truncation. |
|
567 | Set to 0 to disable truncation. | |
583 | """ |
|
568 | """ | |
584 | ).tag(config=True) |
|
569 | ).tag(config=True) | |
585 |
|
570 | |||
586 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
571 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
587 | print_method = ObjectName('_repr_pretty_') |
|
572 | print_method = ObjectName('_repr_pretty_') | |
588 |
|
573 | |||
589 | # Whether to pretty-print or not. |
|
574 | # Whether to pretty-print or not. | |
590 | pprint = Bool(True).tag(config=True) |
|
575 | pprint = Bool(True).tag(config=True) | |
591 |
|
576 | |||
592 | # Whether to be verbose or not. |
|
577 | # Whether to be verbose or not. | |
593 | verbose = Bool(False).tag(config=True) |
|
578 | verbose = Bool(False).tag(config=True) | |
594 |
|
579 | |||
595 | # The maximum width. |
|
580 | # The maximum width. | |
596 | max_width = Integer(79).tag(config=True) |
|
581 | max_width = Integer(79).tag(config=True) | |
597 |
|
582 | |||
598 | # The newline character. |
|
583 | # The newline character. | |
599 | newline = Unicode('\n').tag(config=True) |
|
584 | newline = Unicode('\n').tag(config=True) | |
600 |
|
585 | |||
601 | # format-string for pprinting floats |
|
586 | # format-string for pprinting floats | |
602 | float_format = Unicode('%r') |
|
587 | float_format = Unicode('%r') | |
603 | # setter for float precision, either int or direct format-string |
|
588 | # setter for float precision, either int or direct format-string | |
604 | float_precision = CUnicode('').tag(config=True) |
|
589 | float_precision = CUnicode('').tag(config=True) | |
605 |
|
590 | |||
606 | def _float_precision_changed(self, name, old, new): |
|
591 | def _float_precision_changed(self, name, old, new): | |
607 | """float_precision changed, set float_format accordingly. |
|
592 | """float_precision changed, set float_format accordingly. | |
608 |
|
593 | |||
609 | float_precision can be set by int or str. |
|
594 | float_precision can be set by int or str. | |
610 | This will set float_format, after interpreting input. |
|
595 | This will set float_format, after interpreting input. | |
611 | If numpy has been imported, numpy print precision will also be set. |
|
596 | If numpy has been imported, numpy print precision will also be set. | |
612 |
|
597 | |||
613 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
598 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
614 |
|
599 | |||
615 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
600 | An empty string returns to defaults (repr for float, 8 for numpy). | |
616 |
|
601 | |||
617 | This parameter can be set via the '%precision' magic. |
|
602 | This parameter can be set via the '%precision' magic. | |
618 | """ |
|
603 | """ | |
619 |
|
604 | |||
620 | if '%' in new: |
|
605 | if '%' in new: | |
621 | # got explicit format string |
|
606 | # got explicit format string | |
622 | fmt = new |
|
607 | fmt = new | |
623 | try: |
|
608 | try: | |
624 | fmt%3.14159 |
|
609 | fmt%3.14159 | |
625 | except Exception: |
|
610 | except Exception: | |
626 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
611 | raise ValueError("Precision must be int or format string, not %r"%new) | |
627 | elif new: |
|
612 | elif new: | |
628 | # otherwise, should be an int |
|
613 | # otherwise, should be an int | |
629 | try: |
|
614 | try: | |
630 | i = int(new) |
|
615 | i = int(new) | |
631 | assert i >= 0 |
|
616 | assert i >= 0 | |
632 | except ValueError: |
|
617 | except ValueError: | |
633 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
618 | raise ValueError("Precision must be int or format string, not %r"%new) | |
634 | except AssertionError: |
|
619 | except AssertionError: | |
635 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
620 | raise ValueError("int precision must be non-negative, not %r"%i) | |
636 |
|
621 | |||
637 | fmt = '%%.%if'%i |
|
622 | fmt = '%%.%if'%i | |
638 | if 'numpy' in sys.modules: |
|
623 | if 'numpy' in sys.modules: | |
639 | # set numpy precision if it has been imported |
|
624 | # set numpy precision if it has been imported | |
640 | import numpy |
|
625 | import numpy | |
641 | numpy.set_printoptions(precision=i) |
|
626 | numpy.set_printoptions(precision=i) | |
642 | else: |
|
627 | else: | |
643 | # default back to repr |
|
628 | # default back to repr | |
644 | fmt = '%r' |
|
629 | fmt = '%r' | |
645 | if 'numpy' in sys.modules: |
|
630 | if 'numpy' in sys.modules: | |
646 | import numpy |
|
631 | import numpy | |
647 | # numpy default is 8 |
|
632 | # numpy default is 8 | |
648 | numpy.set_printoptions(precision=8) |
|
633 | numpy.set_printoptions(precision=8) | |
649 | self.float_format = fmt |
|
634 | self.float_format = fmt | |
650 |
|
635 | |||
651 | # Use the default pretty printers from IPython.lib.pretty. |
|
636 | # Use the default pretty printers from IPython.lib.pretty. | |
652 | @default('singleton_printers') |
|
637 | @default('singleton_printers') | |
653 | def _singleton_printers_default(self): |
|
638 | def _singleton_printers_default(self): | |
654 | return pretty._singleton_pprinters.copy() |
|
639 | return pretty._singleton_pprinters.copy() | |
655 |
|
640 | |||
656 | @default('type_printers') |
|
641 | @default('type_printers') | |
657 | def _type_printers_default(self): |
|
642 | def _type_printers_default(self): | |
658 | d = pretty._type_pprinters.copy() |
|
643 | d = pretty._type_pprinters.copy() | |
659 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
644 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
660 | return d |
|
645 | return d | |
661 |
|
646 | |||
662 | @default('deferred_printers') |
|
647 | @default('deferred_printers') | |
663 | def _deferred_printers_default(self): |
|
648 | def _deferred_printers_default(self): | |
664 | return pretty._deferred_type_pprinters.copy() |
|
649 | return pretty._deferred_type_pprinters.copy() | |
665 |
|
650 | |||
666 | #### FormatterABC interface #### |
|
651 | #### FormatterABC interface #### | |
667 |
|
652 | |||
668 | @catch_format_error |
|
653 | @catch_format_error | |
669 | def __call__(self, obj): |
|
654 | def __call__(self, obj): | |
670 | """Compute the pretty representation of the object.""" |
|
655 | """Compute the pretty representation of the object.""" | |
671 | if not self.pprint: |
|
656 | if not self.pprint: | |
672 | return repr(obj) |
|
657 | return repr(obj) | |
673 | else: |
|
658 | else: | |
674 | # handle str and unicode on Python 2 |
|
659 | # handle str and unicode on Python 2 | |
675 | # io.StringIO only accepts unicode, |
|
660 | # io.StringIO only accepts unicode, | |
676 | # cStringIO doesn't handle unicode on py2, |
|
661 | # cStringIO doesn't handle unicode on py2, | |
677 | # StringIO allows str, unicode but only ascii str |
|
662 | # StringIO allows str, unicode but only ascii str | |
678 | stream = pretty.CUnicodeIO() |
|
663 | stream = pretty.CUnicodeIO() | |
679 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
664 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
680 | self.max_width, self.newline, |
|
665 | self.max_width, self.newline, | |
681 | max_seq_length=self.max_seq_length, |
|
666 | max_seq_length=self.max_seq_length, | |
682 | singleton_pprinters=self.singleton_printers, |
|
667 | singleton_pprinters=self.singleton_printers, | |
683 | type_pprinters=self.type_printers, |
|
668 | type_pprinters=self.type_printers, | |
684 | deferred_pprinters=self.deferred_printers) |
|
669 | deferred_pprinters=self.deferred_printers) | |
685 | printer.pretty(obj) |
|
670 | printer.pretty(obj) | |
686 | printer.flush() |
|
671 | printer.flush() | |
687 | return stream.getvalue() |
|
672 | return stream.getvalue() | |
688 |
|
673 | |||
689 |
|
674 | |||
690 | class HTMLFormatter(BaseFormatter): |
|
675 | class HTMLFormatter(BaseFormatter): | |
691 | """An HTML formatter. |
|
676 | """An HTML formatter. | |
692 |
|
677 | |||
693 | To define the callables that compute the HTML representation of your |
|
678 | To define the callables that compute the HTML representation of your | |
694 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
679 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
695 | or :meth:`for_type_by_name` methods to register functions that handle |
|
680 | or :meth:`for_type_by_name` methods to register functions that handle | |
696 | this. |
|
681 | this. | |
697 |
|
682 | |||
698 | The return value of this formatter should be a valid HTML snippet that |
|
683 | The return value of this formatter should be a valid HTML snippet that | |
699 | could be injected into an existing DOM. It should *not* include the |
|
684 | could be injected into an existing DOM. It should *not* include the | |
700 | ```<html>`` or ```<body>`` tags. |
|
685 | ```<html>`` or ```<body>`` tags. | |
701 | """ |
|
686 | """ | |
702 | format_type = Unicode('text/html') |
|
687 | format_type = Unicode('text/html') | |
703 |
|
688 | |||
704 | print_method = ObjectName('_repr_html_') |
|
689 | print_method = ObjectName('_repr_html_') | |
705 |
|
690 | |||
706 |
|
691 | |||
707 | class MarkdownFormatter(BaseFormatter): |
|
692 | class MarkdownFormatter(BaseFormatter): | |
708 | """A Markdown formatter. |
|
693 | """A Markdown formatter. | |
709 |
|
694 | |||
710 | To define the callables that compute the Markdown representation of your |
|
695 | To define the callables that compute the Markdown representation of your | |
711 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` |
|
696 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` | |
712 | or :meth:`for_type_by_name` methods to register functions that handle |
|
697 | or :meth:`for_type_by_name` methods to register functions that handle | |
713 | this. |
|
698 | this. | |
714 |
|
699 | |||
715 | The return value of this formatter should be a valid Markdown. |
|
700 | The return value of this formatter should be a valid Markdown. | |
716 | """ |
|
701 | """ | |
717 | format_type = Unicode('text/markdown') |
|
702 | format_type = Unicode('text/markdown') | |
718 |
|
703 | |||
719 | print_method = ObjectName('_repr_markdown_') |
|
704 | print_method = ObjectName('_repr_markdown_') | |
720 |
|
705 | |||
721 | class SVGFormatter(BaseFormatter): |
|
706 | class SVGFormatter(BaseFormatter): | |
722 | """An SVG formatter. |
|
707 | """An SVG formatter. | |
723 |
|
708 | |||
724 | To define the callables that compute the SVG representation of your |
|
709 | To define the callables that compute the SVG representation of your | |
725 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
710 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
726 | or :meth:`for_type_by_name` methods to register functions that handle |
|
711 | or :meth:`for_type_by_name` methods to register functions that handle | |
727 | this. |
|
712 | this. | |
728 |
|
713 | |||
729 | The return value of this formatter should be valid SVG enclosed in |
|
714 | The return value of this formatter should be valid SVG enclosed in | |
730 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
715 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
731 | *not* include the ```<html>`` or ```<body>`` tags. |
|
716 | *not* include the ```<html>`` or ```<body>`` tags. | |
732 | """ |
|
717 | """ | |
733 | format_type = Unicode('image/svg+xml') |
|
718 | format_type = Unicode('image/svg+xml') | |
734 |
|
719 | |||
735 | print_method = ObjectName('_repr_svg_') |
|
720 | print_method = ObjectName('_repr_svg_') | |
736 |
|
721 | |||
737 |
|
722 | |||
738 | class PNGFormatter(BaseFormatter): |
|
723 | class PNGFormatter(BaseFormatter): | |
739 | """A PNG formatter. |
|
724 | """A PNG formatter. | |
740 |
|
725 | |||
741 | To define the callables that compute the PNG representation of your |
|
726 | To define the callables that compute the PNG representation of your | |
742 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
727 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
743 | or :meth:`for_type_by_name` methods to register functions that handle |
|
728 | or :meth:`for_type_by_name` methods to register functions that handle | |
744 | this. |
|
729 | this. | |
745 |
|
730 | |||
746 | The return value of this formatter should be raw PNG data, *not* |
|
731 | The return value of this formatter should be raw PNG data, *not* | |
747 | base64 encoded. |
|
732 | base64 encoded. | |
748 | """ |
|
733 | """ | |
749 | format_type = Unicode('image/png') |
|
734 | format_type = Unicode('image/png') | |
750 |
|
735 | |||
751 | print_method = ObjectName('_repr_png_') |
|
736 | print_method = ObjectName('_repr_png_') | |
752 |
|
737 | |||
753 | _return_type = (bytes, unicode_type) |
|
738 | _return_type = (bytes, unicode_type) | |
754 |
|
739 | |||
755 |
|
740 | |||
756 | class JPEGFormatter(BaseFormatter): |
|
741 | class JPEGFormatter(BaseFormatter): | |
757 | """A JPEG formatter. |
|
742 | """A JPEG formatter. | |
758 |
|
743 | |||
759 | To define the callables that compute the JPEG representation of your |
|
744 | To define the callables that compute the JPEG representation of your | |
760 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
745 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |
761 | or :meth:`for_type_by_name` methods to register functions that handle |
|
746 | or :meth:`for_type_by_name` methods to register functions that handle | |
762 | this. |
|
747 | this. | |
763 |
|
748 | |||
764 | The return value of this formatter should be raw JPEG data, *not* |
|
749 | The return value of this formatter should be raw JPEG data, *not* | |
765 | base64 encoded. |
|
750 | base64 encoded. | |
766 | """ |
|
751 | """ | |
767 | format_type = Unicode('image/jpeg') |
|
752 | format_type = Unicode('image/jpeg') | |
768 |
|
753 | |||
769 | print_method = ObjectName('_repr_jpeg_') |
|
754 | print_method = ObjectName('_repr_jpeg_') | |
770 |
|
755 | |||
771 | _return_type = (bytes, unicode_type) |
|
756 | _return_type = (bytes, unicode_type) | |
772 |
|
757 | |||
773 |
|
758 | |||
774 | class LatexFormatter(BaseFormatter): |
|
759 | class LatexFormatter(BaseFormatter): | |
775 | """A LaTeX formatter. |
|
760 | """A LaTeX formatter. | |
776 |
|
761 | |||
777 | To define the callables that compute the LaTeX representation of your |
|
762 | To define the callables that compute the LaTeX representation of your | |
778 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
763 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
779 | or :meth:`for_type_by_name` methods to register functions that handle |
|
764 | or :meth:`for_type_by_name` methods to register functions that handle | |
780 | this. |
|
765 | this. | |
781 |
|
766 | |||
782 | The return value of this formatter should be a valid LaTeX equation, |
|
767 | The return value of this formatter should be a valid LaTeX equation, | |
783 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
768 | enclosed in either ```$```, ```$$``` or another LaTeX equation | |
784 | environment. |
|
769 | environment. | |
785 | """ |
|
770 | """ | |
786 | format_type = Unicode('text/latex') |
|
771 | format_type = Unicode('text/latex') | |
787 |
|
772 | |||
788 | print_method = ObjectName('_repr_latex_') |
|
773 | print_method = ObjectName('_repr_latex_') | |
789 |
|
774 | |||
790 |
|
775 | |||
791 | class JSONFormatter(BaseFormatter): |
|
776 | class JSONFormatter(BaseFormatter): | |
792 | """A JSON string formatter. |
|
777 | """A JSON string formatter. | |
793 |
|
778 | |||
794 | To define the callables that compute the JSONable representation of |
|
779 | To define the callables that compute the JSONable representation of | |
795 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
780 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
796 | or :meth:`for_type_by_name` methods to register functions that handle |
|
781 | or :meth:`for_type_by_name` methods to register functions that handle | |
797 | this. |
|
782 | this. | |
798 |
|
783 | |||
799 | The return value of this formatter should be a JSONable list or dict. |
|
784 | The return value of this formatter should be a JSONable list or dict. | |
800 | JSON scalars (None, number, string) are not allowed, only dict or list containers. |
|
785 | JSON scalars (None, number, string) are not allowed, only dict or list containers. | |
801 | """ |
|
786 | """ | |
802 | format_type = Unicode('application/json') |
|
787 | format_type = Unicode('application/json') | |
803 | _return_type = (list, dict) |
|
788 | _return_type = (list, dict) | |
804 |
|
789 | |||
805 | print_method = ObjectName('_repr_json_') |
|
790 | print_method = ObjectName('_repr_json_') | |
806 |
|
791 | |||
807 | def _check_return(self, r, obj): |
|
792 | def _check_return(self, r, obj): | |
808 | """Check that a return value is appropriate |
|
793 | """Check that a return value is appropriate | |
809 |
|
794 | |||
810 | Return the value if so, None otherwise, warning if invalid. |
|
795 | Return the value if so, None otherwise, warning if invalid. | |
811 | """ |
|
796 | """ | |
812 | if r is None: |
|
797 | if r is None: | |
813 | return |
|
798 | return | |
814 | md = None |
|
799 | md = None | |
815 | if isinstance(r, tuple): |
|
800 | if isinstance(r, tuple): | |
816 | # unpack data, metadata tuple for type checking on first element |
|
801 | # unpack data, metadata tuple for type checking on first element | |
817 | r, md = r |
|
802 | r, md = r | |
818 |
|
803 | |||
819 | # handle deprecated JSON-as-string form from IPython < 3 |
|
804 | # handle deprecated JSON-as-string form from IPython < 3 | |
820 | if isinstance(r, string_types): |
|
805 | if isinstance(r, string_types): | |
821 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", |
|
806 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", | |
822 | FormatterWarning) |
|
807 | FormatterWarning) | |
823 | r = json.loads(r) |
|
808 | r = json.loads(r) | |
824 |
|
809 | |||
825 | if md is not None: |
|
810 | if md is not None: | |
826 | # put the tuple back together |
|
811 | # put the tuple back together | |
827 | r = (r, md) |
|
812 | r = (r, md) | |
828 | return super(JSONFormatter, self)._check_return(r, obj) |
|
813 | return super(JSONFormatter, self)._check_return(r, obj) | |
829 |
|
814 | |||
830 |
|
815 | |||
831 | class JavascriptFormatter(BaseFormatter): |
|
816 | class JavascriptFormatter(BaseFormatter): | |
832 | """A Javascript formatter. |
|
817 | """A Javascript formatter. | |
833 |
|
818 | |||
834 | To define the callables that compute the Javascript representation of |
|
819 | To define the callables that compute the Javascript representation of | |
835 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
820 | your objects, define a :meth:`_repr_javascript_` method or use the | |
836 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
821 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
837 | that handle this. |
|
822 | that handle this. | |
838 |
|
823 | |||
839 | The return value of this formatter should be valid Javascript code and |
|
824 | The return value of this formatter should be valid Javascript code and | |
840 | should *not* be enclosed in ```<script>``` tags. |
|
825 | should *not* be enclosed in ```<script>``` tags. | |
841 | """ |
|
826 | """ | |
842 | format_type = Unicode('application/javascript') |
|
827 | format_type = Unicode('application/javascript') | |
843 |
|
828 | |||
844 | print_method = ObjectName('_repr_javascript_') |
|
829 | print_method = ObjectName('_repr_javascript_') | |
845 |
|
830 | |||
846 |
|
831 | |||
847 | class PDFFormatter(BaseFormatter): |
|
832 | class PDFFormatter(BaseFormatter): | |
848 | """A PDF formatter. |
|
833 | """A PDF formatter. | |
849 |
|
834 | |||
850 | To define the callables that compute the PDF representation of your |
|
835 | To define the callables that compute the PDF representation of your | |
851 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
836 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` | |
852 | or :meth:`for_type_by_name` methods to register functions that handle |
|
837 | or :meth:`for_type_by_name` methods to register functions that handle | |
853 | this. |
|
838 | this. | |
854 |
|
839 | |||
855 | The return value of this formatter should be raw PDF data, *not* |
|
840 | The return value of this formatter should be raw PDF data, *not* | |
856 | base64 encoded. |
|
841 | base64 encoded. | |
857 | """ |
|
842 | """ | |
858 | format_type = Unicode('application/pdf') |
|
843 | format_type = Unicode('application/pdf') | |
859 |
|
844 | |||
860 | print_method = ObjectName('_repr_pdf_') |
|
845 | print_method = ObjectName('_repr_pdf_') | |
861 |
|
846 | |||
862 | _return_type = (bytes, unicode_type) |
|
847 | _return_type = (bytes, unicode_type) | |
863 |
|
848 | |||
864 | class IPythonDisplayFormatter(BaseFormatter): |
|
849 | class IPythonDisplayFormatter(BaseFormatter): | |
865 | """A Formatter for objects that know how to display themselves. |
|
850 | """A Formatter for objects that know how to display themselves. | |
866 |
|
851 | |||
867 | To define the callables that compute the representation of your |
|
852 | To define the callables that compute the representation of your | |
868 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` |
|
853 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` | |
869 | or :meth:`for_type_by_name` methods to register functions that handle |
|
854 | or :meth:`for_type_by_name` methods to register functions that handle | |
870 | this. Unlike mime-type displays, this method should not return anything, |
|
855 | this. Unlike mime-type displays, this method should not return anything, | |
871 | instead calling any appropriate display methods itself. |
|
856 | instead calling any appropriate display methods itself. | |
872 |
|
857 | |||
873 | This display formatter has highest priority. |
|
858 | This display formatter has highest priority. | |
874 | If it fires, no other display formatter will be called. |
|
859 | If it fires, no other display formatter will be called. | |
875 | """ |
|
860 | """ | |
876 | print_method = ObjectName('_ipython_display_') |
|
861 | print_method = ObjectName('_ipython_display_') | |
877 | _return_type = (type(None), bool) |
|
862 | _return_type = (type(None), bool) | |
878 |
|
863 | |||
879 |
|
864 | |||
880 | @catch_format_error |
|
865 | @catch_format_error | |
881 | def __call__(self, obj): |
|
866 | def __call__(self, obj): | |
882 | """Compute the format for an object.""" |
|
867 | """Compute the format for an object.""" | |
883 | if self.enabled: |
|
868 | if self.enabled: | |
884 | # lookup registered printer |
|
869 | # lookup registered printer | |
885 | try: |
|
870 | try: | |
886 | printer = self.lookup(obj) |
|
871 | printer = self.lookup(obj) | |
887 | except KeyError: |
|
872 | except KeyError: | |
888 | pass |
|
873 | pass | |
889 | else: |
|
874 | else: | |
890 | printer(obj) |
|
875 | printer(obj) | |
891 | return True |
|
876 | return True | |
892 | # Finally look for special method names |
|
877 | # Finally look for special method names | |
893 | method = get_real_method(obj, self.print_method) |
|
878 | method = get_real_method(obj, self.print_method) | |
894 | if method is not None: |
|
879 | if method is not None: | |
895 | method() |
|
880 | method() | |
896 | return True |
|
881 | return True | |
897 |
|
882 | |||
898 |
|
883 | |||
899 | FormatterABC.register(BaseFormatter) |
|
884 | FormatterABC.register(BaseFormatter) | |
900 | FormatterABC.register(PlainTextFormatter) |
|
885 | FormatterABC.register(PlainTextFormatter) | |
901 | FormatterABC.register(HTMLFormatter) |
|
886 | FormatterABC.register(HTMLFormatter) | |
902 | FormatterABC.register(MarkdownFormatter) |
|
887 | FormatterABC.register(MarkdownFormatter) | |
903 | FormatterABC.register(SVGFormatter) |
|
888 | FormatterABC.register(SVGFormatter) | |
904 | FormatterABC.register(PNGFormatter) |
|
889 | FormatterABC.register(PNGFormatter) | |
905 | FormatterABC.register(PDFFormatter) |
|
890 | FormatterABC.register(PDFFormatter) | |
906 | FormatterABC.register(JPEGFormatter) |
|
891 | FormatterABC.register(JPEGFormatter) | |
907 | FormatterABC.register(LatexFormatter) |
|
892 | FormatterABC.register(LatexFormatter) | |
908 | FormatterABC.register(JSONFormatter) |
|
893 | FormatterABC.register(JSONFormatter) | |
909 | FormatterABC.register(JavascriptFormatter) |
|
894 | FormatterABC.register(JavascriptFormatter) | |
910 | FormatterABC.register(IPythonDisplayFormatter) |
|
895 | FormatterABC.register(IPythonDisplayFormatter) | |
911 |
|
896 | |||
912 |
|
897 | |||
913 | def format_display_data(obj, include=None, exclude=None): |
|
898 | def format_display_data(obj, include=None, exclude=None): | |
914 | """Return a format data dict for an object. |
|
899 | """Return a format data dict for an object. | |
915 |
|
900 | |||
916 | By default all format types will be computed. |
|
901 | By default all format types will be computed. | |
917 |
|
902 | |||
918 | The following MIME types are currently implemented: |
|
903 | The following MIME types are currently implemented: | |
919 |
|
904 | |||
920 | * text/plain |
|
905 | * text/plain | |
921 | * text/html |
|
906 | * text/html | |
922 | * text/markdown |
|
907 | * text/markdown | |
923 | * text/latex |
|
908 | * text/latex | |
924 | * application/json |
|
909 | * application/json | |
925 | * application/javascript |
|
910 | * application/javascript | |
926 | * application/pdf |
|
911 | * application/pdf | |
927 | * image/png |
|
912 | * image/png | |
928 | * image/jpeg |
|
913 | * image/jpeg | |
929 | * image/svg+xml |
|
914 | * image/svg+xml | |
930 |
|
915 | |||
931 | Parameters |
|
916 | Parameters | |
932 | ---------- |
|
917 | ---------- | |
933 | obj : object |
|
918 | obj : object | |
934 | The Python object whose format data will be computed. |
|
919 | The Python object whose format data will be computed. | |
935 |
|
920 | |||
936 | Returns |
|
921 | Returns | |
937 | ------- |
|
922 | ------- | |
938 | format_dict : dict |
|
923 | format_dict : dict | |
939 | A dictionary of key/value pairs, one or each format that was |
|
924 | A dictionary of key/value pairs, one or each format that was | |
940 | generated for the object. The keys are the format types, which |
|
925 | generated for the object. The keys are the format types, which | |
941 | will usually be MIME type strings and the values and JSON'able |
|
926 | will usually be MIME type strings and the values and JSON'able | |
942 | data structure containing the raw data for the representation in |
|
927 | data structure containing the raw data for the representation in | |
943 | that format. |
|
928 | that format. | |
944 | include : list or tuple, optional |
|
929 | include : list or tuple, optional | |
945 | A list of format type strings (MIME types) to include in the |
|
930 | A list of format type strings (MIME types) to include in the | |
946 | format data dict. If this is set *only* the format types included |
|
931 | format data dict. If this is set *only* the format types included | |
947 | in this list will be computed. |
|
932 | in this list will be computed. | |
948 | exclude : list or tuple, optional |
|
933 | exclude : list or tuple, optional | |
949 | A list of format type string (MIME types) to exclue in the format |
|
934 | A list of format type string (MIME types) to exclue in the format | |
950 | data dict. If this is set all format types will be computed, |
|
935 | data dict. If this is set all format types will be computed, | |
951 | except for those included in this argument. |
|
936 | except for those included in this argument. | |
952 | """ |
|
937 | """ | |
953 | from IPython.core.interactiveshell import InteractiveShell |
|
938 | from IPython.core.interactiveshell import InteractiveShell | |
954 |
|
939 | |||
955 | return InteractiveShell.instance().display_formatter.format( |
|
940 | return InteractiveShell.instance().display_formatter.format( | |
956 | obj, |
|
941 | obj, | |
957 | include, |
|
942 | include, | |
958 | exclude |
|
943 | exclude | |
959 | ) |
|
944 | ) | |
960 |
|
945 |
General Comments 0
You need to be logged in to leave comments.
Login now