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