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