Show More
@@ -1,593 +1,596 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Robert Kern |
|
7 | * Robert Kern | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2010, IPython Development Team. |
|
11 | # Copyright (c) 2010, IPython Development Team. | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
14 | # | |
15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
15 | # The full license is in the file COPYING.txt, distributed with this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | # Stdlib imports |
|
22 | # Stdlib imports | |
23 | import abc |
|
23 | import abc | |
24 | import sys |
|
24 | import sys | |
25 | # We must use StringIO, as cStringIO doesn't handle unicode properly. |
|
25 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
26 | from StringIO import StringIO |
|
26 | from StringIO import StringIO | |
27 |
|
27 | |||
28 | # Our own imports |
|
28 | # Our own imports | |
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.lib import pretty |
|
30 | from IPython.lib import pretty | |
31 | from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName |
|
31 | from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # The main DisplayFormatter class |
|
35 | # The main DisplayFormatter class | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class DisplayFormatter(Configurable): |
|
39 | class DisplayFormatter(Configurable): | |
40 |
|
40 | |||
41 | # When set to true only the default plain text formatter will be used. |
|
41 | # When set to true only the default plain text formatter will be used. | |
42 | plain_text_only = Bool(False, config=True) |
|
42 | plain_text_only = Bool(False, config=True) | |
43 |
|
43 | |||
44 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
44 | # A dict of formatter whose keys are format types (MIME types) and whose | |
45 | # values are subclasses of BaseFormatter. |
|
45 | # values are subclasses of BaseFormatter. | |
46 | formatters = Dict(config=True) |
|
46 | formatters = Dict(config=True) | |
47 | def _formatters_default(self): |
|
47 | def _formatters_default(self): | |
48 | """Activate the default formatters.""" |
|
48 | """Activate the default formatters.""" | |
49 | formatter_classes = [ |
|
49 | formatter_classes = [ | |
50 | PlainTextFormatter, |
|
50 | PlainTextFormatter, | |
51 | HTMLFormatter, |
|
51 | HTMLFormatter, | |
52 | SVGFormatter, |
|
52 | SVGFormatter, | |
53 | PNGFormatter, |
|
53 | PNGFormatter, | |
54 | LatexFormatter, |
|
54 | LatexFormatter, | |
55 | JSONFormatter, |
|
55 | JSONFormatter, | |
56 | JavascriptFormatter |
|
56 | JavascriptFormatter | |
57 | ] |
|
57 | ] | |
58 | d = {} |
|
58 | d = {} | |
59 | for cls in formatter_classes: |
|
59 | for cls in formatter_classes: | |
60 | f = cls(config=self.config) |
|
60 | f = cls(config=self.config) | |
61 | d[f.format_type] = f |
|
61 | d[f.format_type] = f | |
62 | return d |
|
62 | return d | |
63 |
|
63 | |||
64 | def format(self, obj, include=None, exclude=None): |
|
64 | def format(self, obj, include=None, exclude=None): | |
65 | """Return a format data dict for an object. |
|
65 | """Return a format data dict for an object. | |
66 |
|
66 | |||
67 | By default all format types will be computed. |
|
67 | By default all format types will be computed. | |
68 |
|
68 | |||
69 | The following MIME types are currently implemented: |
|
69 | The following MIME types are currently implemented: | |
70 |
|
70 | |||
71 | * text/plain |
|
71 | * text/plain | |
72 | * text/html |
|
72 | * text/html | |
73 | * text/latex |
|
73 | * text/latex | |
74 | * application/json |
|
74 | * application/json | |
75 | * image/png |
|
75 | * image/png | |
76 | * immage/svg+xml |
|
76 | * immage/svg+xml | |
77 |
|
77 | |||
78 | Parameters |
|
78 | Parameters | |
79 | ---------- |
|
79 | ---------- | |
80 | obj : object |
|
80 | obj : object | |
81 | The Python object whose format data will be computed. |
|
81 | The Python object whose format data will be computed. | |
82 | include : list or tuple, optional |
|
82 | include : list or tuple, optional | |
83 | A list of format type strings (MIME types) to include in the |
|
83 | A list of format type strings (MIME types) to include in the | |
84 | format data dict. If this is set *only* the format types included |
|
84 | format data dict. If this is set *only* the format types included | |
85 | in this list will be computed. |
|
85 | in this list will be computed. | |
86 | exclude : list or tuple, optional |
|
86 | exclude : list or tuple, optional | |
87 | A list of format type string (MIME types) to exclue in the format |
|
87 | A list of format type string (MIME types) to exclue in the format | |
88 | data dict. If this is set all format types will be computed, |
|
88 | data dict. If this is set all format types will be computed, | |
89 | except for those included in this argument. |
|
89 | except for those included in this argument. | |
90 |
|
90 | |||
91 | Returns |
|
91 | Returns | |
92 | ------- |
|
92 | ------- | |
93 | format_dict : dict |
|
93 | format_dict : dict | |
94 | A dictionary of key/value pairs, one or each format that was |
|
94 | A dictionary of key/value pairs, one or each format that was | |
95 | generated for the object. The keys are the format types, which |
|
95 | generated for the object. The keys are the format types, which | |
96 | will usually be MIME type strings and the values and JSON'able |
|
96 | will usually be MIME type strings and the values and JSON'able | |
97 | data structure containing the raw data for the representation in |
|
97 | data structure containing the raw data for the representation in | |
98 | that format. |
|
98 | that format. | |
99 | """ |
|
99 | """ | |
100 | format_dict = {} |
|
100 | format_dict = {} | |
101 |
|
101 | |||
102 | # If plain text only is active |
|
102 | # If plain text only is active | |
103 | if self.plain_text_only: |
|
103 | if self.plain_text_only: | |
104 | formatter = self.formatters['text/plain'] |
|
104 | formatter = self.formatters['text/plain'] | |
105 | try: |
|
105 | try: | |
106 | data = formatter(obj) |
|
106 | data = formatter(obj) | |
107 | except: |
|
107 | except: | |
108 | # FIXME: log the exception |
|
108 | # FIXME: log the exception | |
109 | raise |
|
109 | raise | |
110 | if data is not None: |
|
110 | if data is not None: | |
111 | format_dict['text/plain'] = data |
|
111 | format_dict['text/plain'] = data | |
112 | return format_dict |
|
112 | return format_dict | |
113 |
|
113 | |||
114 | for format_type, formatter in self.formatters.items(): |
|
114 | for format_type, formatter in self.formatters.items(): | |
115 | if include is not None: |
|
115 | if include is not None: | |
116 | if format_type not in include: |
|
116 | if format_type not in include: | |
117 | continue |
|
117 | continue | |
118 | if exclude is not None: |
|
118 | if exclude is not None: | |
119 | if format_type in exclude: |
|
119 | if format_type in exclude: | |
120 | continue |
|
120 | continue | |
121 | try: |
|
121 | try: | |
122 | data = formatter(obj) |
|
122 | data = formatter(obj) | |
123 | except: |
|
123 | except: | |
124 | # FIXME: log the exception |
|
124 | # FIXME: log the exception | |
125 | raise |
|
125 | raise | |
126 | if data is not None: |
|
126 | if data is not None: | |
127 | format_dict[format_type] = data |
|
127 | format_dict[format_type] = data | |
128 | return format_dict |
|
128 | return format_dict | |
129 |
|
129 | |||
130 | @property |
|
130 | @property | |
131 | def format_types(self): |
|
131 | def format_types(self): | |
132 | """Return the format types (MIME types) of the active formatters.""" |
|
132 | """Return the format types (MIME types) of the active formatters.""" | |
133 | return self.formatters.keys() |
|
133 | return self.formatters.keys() | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | #----------------------------------------------------------------------------- |
|
136 | #----------------------------------------------------------------------------- | |
137 | # Formatters for specific format types (text, html, svg, etc.) |
|
137 | # Formatters for specific format types (text, html, svg, etc.) | |
138 | #----------------------------------------------------------------------------- |
|
138 | #----------------------------------------------------------------------------- | |
139 |
|
139 | |||
140 |
|
140 | |||
141 | class FormatterABC(object): |
|
141 | class FormatterABC(object): | |
142 | """ Abstract base class for Formatters. |
|
142 | """ Abstract base class for Formatters. | |
143 |
|
143 | |||
144 | A formatter is a callable class that is responsible for computing the |
|
144 | A formatter is a callable class that is responsible for computing the | |
145 | raw format data for a particular format type (MIME type). For example, |
|
145 | raw format data for a particular format type (MIME type). For example, | |
146 | an HTML formatter would have a format type of `text/html` and would return |
|
146 | an HTML formatter would have a format type of `text/html` and would return | |
147 | the HTML representation of the object when called. |
|
147 | the HTML representation of the object when called. | |
148 | """ |
|
148 | """ | |
149 | __metaclass__ = abc.ABCMeta |
|
149 | __metaclass__ = abc.ABCMeta | |
150 |
|
150 | |||
151 | # The format type of the data returned, usually a MIME type. |
|
151 | # The format type of the data returned, usually a MIME type. | |
152 | format_type = 'text/plain' |
|
152 | format_type = 'text/plain' | |
153 |
|
153 | |||
154 | # Is the formatter enabled... |
|
154 | # Is the formatter enabled... | |
155 | enabled = True |
|
155 | enabled = True | |
156 |
|
156 | |||
157 | @abc.abstractmethod |
|
157 | @abc.abstractmethod | |
158 | def __call__(self, obj): |
|
158 | def __call__(self, obj): | |
159 | """Return a JSON'able representation of the object. |
|
159 | """Return a JSON'able representation of the object. | |
160 |
|
160 | |||
161 | If the object cannot be formatted by this formatter, then return None |
|
161 | If the object cannot be formatted by this formatter, then return None | |
162 | """ |
|
162 | """ | |
163 | try: |
|
163 | try: | |
164 | return repr(obj) |
|
164 | return repr(obj) | |
165 | except TypeError: |
|
165 | except TypeError: | |
166 | return None |
|
166 | return None | |
167 |
|
167 | |||
168 |
|
168 | |||
169 | class BaseFormatter(Configurable): |
|
169 | class BaseFormatter(Configurable): | |
170 | """A base formatter class that is configurable. |
|
170 | """A base formatter class that is configurable. | |
171 |
|
171 | |||
172 | This formatter should usually be used as the base class of all formatters. |
|
172 | This formatter should usually be used as the base class of all formatters. | |
173 | It is a traited :class:`Configurable` class and includes an extensible |
|
173 | It is a traited :class:`Configurable` class and includes an extensible | |
174 | API for users to determine how their objects are formatted. The following |
|
174 | API for users to determine how their objects are formatted. The following | |
175 | logic is used to find a function to format an given object. |
|
175 | logic is used to find a function to format an given object. | |
176 |
|
176 | |||
177 | 1. The object is introspected to see if it has a method with the name |
|
177 | 1. The object is introspected to see if it has a method with the name | |
178 | :attr:`print_method`. If is does, that object is passed to that method |
|
178 | :attr:`print_method`. If is does, that object is passed to that method | |
179 | for formatting. |
|
179 | for formatting. | |
180 | 2. If no print method is found, three internal dictionaries are consulted |
|
180 | 2. If no print method is found, three internal dictionaries are consulted | |
181 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
181 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
182 | and :attr:`deferred_printers`. |
|
182 | and :attr:`deferred_printers`. | |
183 |
|
183 | |||
184 | Users should use these dictionaries to register functions that will be |
|
184 | Users should use these dictionaries to register functions that will be | |
185 | used to compute the format data for their objects (if those objects don't |
|
185 | used to compute the format data for their objects (if those objects don't | |
186 | have the special print methods). The easiest way of using these |
|
186 | have the special print methods). The easiest way of using these | |
187 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
187 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
188 | methods. |
|
188 | methods. | |
189 |
|
189 | |||
190 | If no function/callable is found to compute the format data, ``None`` is |
|
190 | If no function/callable is found to compute the format data, ``None`` is | |
191 | returned and this format type is not used. |
|
191 | returned and this format type is not used. | |
192 | """ |
|
192 | """ | |
193 |
|
193 | |||
194 | format_type = Unicode('text/plain') |
|
194 | format_type = Unicode('text/plain') | |
195 |
|
195 | |||
196 | enabled = Bool(True, config=True) |
|
196 | enabled = Bool(True, config=True) | |
197 |
|
197 | |||
198 | print_method = ObjectName('__repr__') |
|
198 | print_method = ObjectName('__repr__') | |
199 |
|
199 | |||
200 | # The singleton printers. |
|
200 | # The singleton printers. | |
201 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
201 | # Maps the IDs of the builtin singleton objects to the format functions. | |
202 | singleton_printers = Dict(config=True) |
|
202 | singleton_printers = Dict(config=True) | |
203 | def _singleton_printers_default(self): |
|
203 | def _singleton_printers_default(self): | |
204 | return {} |
|
204 | return {} | |
205 |
|
205 | |||
206 | # The type-specific printers. |
|
206 | # The type-specific printers. | |
207 | # Map type objects to the format functions. |
|
207 | # Map type objects to the format functions. | |
208 | type_printers = Dict(config=True) |
|
208 | type_printers = Dict(config=True) | |
209 | def _type_printers_default(self): |
|
209 | def _type_printers_default(self): | |
210 | return {} |
|
210 | return {} | |
211 |
|
211 | |||
212 | # The deferred-import type-specific printers. |
|
212 | # The deferred-import type-specific printers. | |
213 | # Map (modulename, classname) pairs to the format functions. |
|
213 | # Map (modulename, classname) pairs to the format functions. | |
214 | deferred_printers = Dict(config=True) |
|
214 | deferred_printers = Dict(config=True) | |
215 | def _deferred_printers_default(self): |
|
215 | def _deferred_printers_default(self): | |
216 | return {} |
|
216 | return {} | |
217 |
|
217 | |||
218 | def __call__(self, obj): |
|
218 | def __call__(self, obj): | |
219 | """Compute the format for an object.""" |
|
219 | """Compute the format for an object.""" | |
220 | if self.enabled: |
|
220 | if self.enabled: | |
221 | obj_id = id(obj) |
|
221 | obj_id = id(obj) | |
222 | try: |
|
222 | try: | |
223 | obj_class = getattr(obj, '__class__', None) or type(obj) |
|
223 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
224 | # First try to find registered singleton printers for the type. |
|
224 | # First try to find registered singleton printers for the type. | |
225 | try: |
|
225 | try: | |
226 | printer = self.singleton_printers[obj_id] |
|
226 | printer = self.singleton_printers[obj_id] | |
227 | except (TypeError, KeyError): |
|
227 | except (TypeError, KeyError): | |
228 | pass |
|
228 | pass | |
229 | else: |
|
229 | else: | |
230 | return printer(obj) |
|
230 | return printer(obj) | |
231 | # Next look for type_printers. |
|
231 | # Next look for type_printers. | |
232 | for cls in pretty._get_mro(obj_class): |
|
232 | for cls in pretty._get_mro(obj_class): | |
233 | if cls in self.type_printers: |
|
233 | if cls in self.type_printers: | |
234 | return self.type_printers[cls](obj) |
|
234 | return self.type_printers[cls](obj) | |
235 | else: |
|
235 | else: | |
236 | printer = self._in_deferred_types(cls) |
|
236 | printer = self._in_deferred_types(cls) | |
237 | if printer is not None: |
|
237 | if printer is not None: | |
238 | return printer(obj) |
|
238 | return printer(obj) | |
239 | # Finally look for special method names. |
|
239 | # Finally look for special method names. | |
240 | if hasattr(obj_class, self.print_method): |
|
240 | if hasattr(obj_class, self.print_method): | |
241 | printer = getattr(obj_class, self.print_method) |
|
241 | printer = getattr(obj_class, self.print_method) | |
242 | return printer(obj) |
|
242 | return printer(obj) | |
243 | return None |
|
243 | return None | |
244 | except Exception: |
|
244 | except Exception: | |
245 | pass |
|
245 | pass | |
246 | else: |
|
246 | else: | |
247 | return None |
|
247 | return None | |
248 |
|
248 | |||
249 | def for_type(self, typ, func): |
|
249 | def for_type(self, typ, func): | |
250 | """Add a format function for a given type. |
|
250 | """Add a format function for a given type. | |
251 |
|
251 | |||
252 | Parameters |
|
252 | Parameters | |
253 | ----------- |
|
253 | ----------- | |
254 | typ : class |
|
254 | typ : class | |
255 | The class of the object that will be formatted using `func`. |
|
255 | The class of the object that will be formatted using `func`. | |
256 | func : callable |
|
256 | func : callable | |
257 | The callable that will be called to compute the format data. The |
|
257 | The callable that will be called to compute the format data. The | |
258 | call signature of this function is simple, it must take the |
|
258 | call signature of this function is simple, it must take the | |
259 | object to be formatted and return the raw data for the given |
|
259 | object to be formatted and return the raw data for the given | |
260 | format. Subclasses may use a different call signature for the |
|
260 | format. Subclasses may use a different call signature for the | |
261 | `func` argument. |
|
261 | `func` argument. | |
262 | """ |
|
262 | """ | |
263 | oldfunc = self.type_printers.get(typ, None) |
|
263 | oldfunc = self.type_printers.get(typ, None) | |
264 | if func is not None: |
|
264 | if func is not None: | |
265 | # To support easy restoration of old printers, we need to ignore |
|
265 | # To support easy restoration of old printers, we need to ignore | |
266 | # Nones. |
|
266 | # Nones. | |
267 | self.type_printers[typ] = func |
|
267 | self.type_printers[typ] = func | |
268 | return oldfunc |
|
268 | return oldfunc | |
269 |
|
269 | |||
270 | def for_type_by_name(self, type_module, type_name, func): |
|
270 | def for_type_by_name(self, type_module, type_name, func): | |
271 | """Add a format function for a type specified by the full dotted |
|
271 | """Add a format function for a type specified by the full dotted | |
272 | module and name of the type, rather than the type of the object. |
|
272 | module and name of the type, rather than the type of the object. | |
273 |
|
273 | |||
274 | Parameters |
|
274 | Parameters | |
275 | ---------- |
|
275 | ---------- | |
276 | type_module : str |
|
276 | type_module : str | |
277 | The full dotted name of the module the type is defined in, like |
|
277 | The full dotted name of the module the type is defined in, like | |
278 | ``numpy``. |
|
278 | ``numpy``. | |
279 | type_name : str |
|
279 | type_name : str | |
280 | The name of the type (the class name), like ``dtype`` |
|
280 | The name of the type (the class name), like ``dtype`` | |
281 | func : callable |
|
281 | func : callable | |
282 | The callable that will be called to compute the format data. The |
|
282 | The callable that will be called to compute the format data. The | |
283 | call signature of this function is simple, it must take the |
|
283 | call signature of this function is simple, it must take the | |
284 | object to be formatted and return the raw data for the given |
|
284 | object to be formatted and return the raw data for the given | |
285 | format. Subclasses may use a different call signature for the |
|
285 | format. Subclasses may use a different call signature for the | |
286 | `func` argument. |
|
286 | `func` argument. | |
287 | """ |
|
287 | """ | |
288 | key = (type_module, type_name) |
|
288 | key = (type_module, type_name) | |
289 | oldfunc = self.deferred_printers.get(key, None) |
|
289 | oldfunc = self.deferred_printers.get(key, None) | |
290 | if func is not None: |
|
290 | if func is not None: | |
291 | # To support easy restoration of old printers, we need to ignore |
|
291 | # To support easy restoration of old printers, we need to ignore | |
292 | # Nones. |
|
292 | # Nones. | |
293 | self.deferred_printers[key] = func |
|
293 | self.deferred_printers[key] = func | |
294 | return oldfunc |
|
294 | return oldfunc | |
295 |
|
295 | |||
296 | def _in_deferred_types(self, cls): |
|
296 | def _in_deferred_types(self, cls): | |
297 | """ |
|
297 | """ | |
298 | Check if the given class is specified in the deferred type registry. |
|
298 | Check if the given class is specified in the deferred type registry. | |
299 |
|
299 | |||
300 | Returns the printer from the registry if it exists, and None if the |
|
300 | Returns the printer from the registry if it exists, and None if the | |
301 | class is not in the registry. Successful matches will be moved to the |
|
301 | class is not in the registry. Successful matches will be moved to the | |
302 | regular type registry for future use. |
|
302 | regular type registry for future use. | |
303 | """ |
|
303 | """ | |
304 | mod = getattr(cls, '__module__', None) |
|
304 | mod = getattr(cls, '__module__', None) | |
305 | name = getattr(cls, '__name__', None) |
|
305 | name = getattr(cls, '__name__', None) | |
306 | key = (mod, name) |
|
306 | key = (mod, name) | |
307 | printer = None |
|
307 | printer = None | |
308 | if key in self.deferred_printers: |
|
308 | if key in self.deferred_printers: | |
309 | # Move the printer over to the regular registry. |
|
309 | # Move the printer over to the regular registry. | |
310 | printer = self.deferred_printers.pop(key) |
|
310 | printer = self.deferred_printers.pop(key) | |
311 | self.type_printers[cls] = printer |
|
311 | self.type_printers[cls] = printer | |
312 | return printer |
|
312 | return printer | |
313 |
|
313 | |||
314 |
|
314 | |||
315 | class PlainTextFormatter(BaseFormatter): |
|
315 | class PlainTextFormatter(BaseFormatter): | |
316 | """The default pretty-printer. |
|
316 | """The default pretty-printer. | |
317 |
|
317 | |||
318 | This uses :mod:`IPython.external.pretty` to compute the format data of |
|
318 | This uses :mod:`IPython.external.pretty` to compute the format data of | |
319 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
319 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
320 | See the documentation of :mod:`IPython.external.pretty` for details on |
|
320 | See the documentation of :mod:`IPython.external.pretty` for details on | |
321 | how to write pretty printers. Here is a simple example:: |
|
321 | how to write pretty printers. Here is a simple example:: | |
322 |
|
322 | |||
323 | def dtype_pprinter(obj, p, cycle): |
|
323 | def dtype_pprinter(obj, p, cycle): | |
324 | if cycle: |
|
324 | if cycle: | |
325 | return p.text('dtype(...)') |
|
325 | return p.text('dtype(...)') | |
326 | if hasattr(obj, 'fields'): |
|
326 | if hasattr(obj, 'fields'): | |
327 | if obj.fields is None: |
|
327 | if obj.fields is None: | |
328 | p.text(repr(obj)) |
|
328 | p.text(repr(obj)) | |
329 | else: |
|
329 | else: | |
330 | p.begin_group(7, 'dtype([') |
|
330 | p.begin_group(7, 'dtype([') | |
331 | for i, field in enumerate(obj.descr): |
|
331 | for i, field in enumerate(obj.descr): | |
332 | if i > 0: |
|
332 | if i > 0: | |
333 | p.text(',') |
|
333 | p.text(',') | |
334 | p.breakable() |
|
334 | p.breakable() | |
335 | p.pretty(field) |
|
335 | p.pretty(field) | |
336 | p.end_group(7, '])') |
|
336 | p.end_group(7, '])') | |
337 | """ |
|
337 | """ | |
338 |
|
338 | |||
339 | # The format type of data returned. |
|
339 | # The format type of data returned. | |
340 | format_type = Unicode('text/plain') |
|
340 | format_type = Unicode('text/plain') | |
341 |
|
341 | |||
342 | # This subclass ignores this attribute as it always need to return |
|
342 | # This subclass ignores this attribute as it always need to return | |
343 | # something. |
|
343 | # something. | |
344 | enabled = Bool(True, config=False) |
|
344 | enabled = Bool(True, config=False) | |
345 |
|
345 | |||
346 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
346 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
347 | print_method = ObjectName('_repr_pretty_') |
|
347 | print_method = ObjectName('_repr_pretty_') | |
348 |
|
348 | |||
349 | # Whether to pretty-print or not. |
|
349 | # Whether to pretty-print or not. | |
350 | pprint = Bool(True, config=True) |
|
350 | pprint = Bool(True, config=True) | |
351 |
|
351 | |||
352 | # Whether to be verbose or not. |
|
352 | # Whether to be verbose or not. | |
353 | verbose = Bool(False, config=True) |
|
353 | verbose = Bool(False, config=True) | |
354 |
|
354 | |||
355 | # The maximum width. |
|
355 | # The maximum width. | |
356 | max_width = Int(79, config=True) |
|
356 | max_width = Int(79, config=True) | |
357 |
|
357 | |||
358 | # The newline character. |
|
358 | # The newline character. | |
359 | newline = Unicode('\n', config=True) |
|
359 | newline = Unicode('\n', config=True) | |
360 |
|
360 | |||
361 | # format-string for pprinting floats |
|
361 | # format-string for pprinting floats | |
362 | float_format = Unicode('%r') |
|
362 | float_format = Unicode('%r') | |
363 | # setter for float precision, either int or direct format-string |
|
363 | # setter for float precision, either int or direct format-string | |
364 | float_precision = CUnicode('', config=True) |
|
364 | float_precision = CUnicode('', config=True) | |
365 |
|
365 | |||
366 | def _float_precision_changed(self, name, old, new): |
|
366 | def _float_precision_changed(self, name, old, new): | |
367 | """float_precision changed, set float_format accordingly. |
|
367 | """float_precision changed, set float_format accordingly. | |
368 |
|
368 | |||
369 | float_precision can be set by int or str. |
|
369 | float_precision can be set by int or str. | |
370 | This will set float_format, after interpreting input. |
|
370 | This will set float_format, after interpreting input. | |
371 | If numpy has been imported, numpy print precision will also be set. |
|
371 | If numpy has been imported, numpy print precision will also be set. | |
372 |
|
372 | |||
373 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
373 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
374 |
|
374 | |||
375 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
375 | An empty string returns to defaults (repr for float, 8 for numpy). | |
376 |
|
376 | |||
377 | This parameter can be set via the '%precision' magic. |
|
377 | This parameter can be set via the '%precision' magic. | |
378 | """ |
|
378 | """ | |
379 |
|
379 | |||
380 | if '%' in new: |
|
380 | if '%' in new: | |
381 | # got explicit format string |
|
381 | # got explicit format string | |
382 | fmt = new |
|
382 | fmt = new | |
383 | try: |
|
383 | try: | |
384 | fmt%3.14159 |
|
384 | fmt%3.14159 | |
385 | except Exception: |
|
385 | except Exception: | |
386 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
386 | raise ValueError("Precision must be int or format string, not %r"%new) | |
387 | elif new: |
|
387 | elif new: | |
388 | # otherwise, should be an int |
|
388 | # otherwise, should be an int | |
389 | try: |
|
389 | try: | |
390 | i = int(new) |
|
390 | i = int(new) | |
391 | assert i >= 0 |
|
391 | assert i >= 0 | |
392 | except ValueError: |
|
392 | except ValueError: | |
393 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
393 | raise ValueError("Precision must be int or format string, not %r"%new) | |
394 | except AssertionError: |
|
394 | except AssertionError: | |
395 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
395 | raise ValueError("int precision must be non-negative, not %r"%i) | |
396 |
|
396 | |||
397 | fmt = '%%.%if'%i |
|
397 | fmt = '%%.%if'%i | |
398 | if 'numpy' in sys.modules: |
|
398 | if 'numpy' in sys.modules: | |
399 | # set numpy precision if it has been imported |
|
399 | # set numpy precision if it has been imported | |
400 | import numpy |
|
400 | import numpy | |
401 | numpy.set_printoptions(precision=i) |
|
401 | numpy.set_printoptions(precision=i) | |
402 | else: |
|
402 | else: | |
403 | # default back to repr |
|
403 | # default back to repr | |
404 | fmt = '%r' |
|
404 | fmt = '%r' | |
405 | if 'numpy' in sys.modules: |
|
405 | if 'numpy' in sys.modules: | |
406 | import numpy |
|
406 | import numpy | |
407 | # numpy default is 8 |
|
407 | # numpy default is 8 | |
408 | numpy.set_printoptions(precision=8) |
|
408 | numpy.set_printoptions(precision=8) | |
409 | self.float_format = fmt |
|
409 | self.float_format = fmt | |
410 |
|
410 | |||
411 | # Use the default pretty printers from IPython.external.pretty. |
|
411 | # Use the default pretty printers from IPython.external.pretty. | |
412 | def _singleton_printers_default(self): |
|
412 | def _singleton_printers_default(self): | |
413 | return pretty._singleton_pprinters.copy() |
|
413 | return pretty._singleton_pprinters.copy() | |
414 |
|
414 | |||
415 | def _type_printers_default(self): |
|
415 | def _type_printers_default(self): | |
416 | d = pretty._type_pprinters.copy() |
|
416 | d = pretty._type_pprinters.copy() | |
417 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
417 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
418 | return d |
|
418 | return d | |
419 |
|
419 | |||
420 | def _deferred_printers_default(self): |
|
420 | def _deferred_printers_default(self): | |
421 | return pretty._deferred_type_pprinters.copy() |
|
421 | return pretty._deferred_type_pprinters.copy() | |
422 |
|
422 | |||
423 | #### FormatterABC interface #### |
|
423 | #### FormatterABC interface #### | |
424 |
|
424 | |||
425 | def __call__(self, obj): |
|
425 | def __call__(self, obj): | |
426 | """Compute the pretty representation of the object.""" |
|
426 | """Compute the pretty representation of the object.""" | |
427 | if not self.pprint: |
|
427 | if not self.pprint: | |
428 | try: |
|
428 | try: | |
429 | return repr(obj) |
|
429 | return repr(obj) | |
430 | except TypeError: |
|
430 | except TypeError: | |
431 | return '' |
|
431 | return '' | |
432 | else: |
|
432 | else: | |
433 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
433 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
434 | stream = StringIO() |
|
434 | stream = StringIO() | |
|
435 | # self.newline.encode() is a quick fix for issue gh-597. We need to | |||
|
436 | # ensure that stream does not get a mix of unicode and bytestrings, | |||
|
437 | # or it will cause trouble. | |||
435 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
438 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
436 | self.max_width, self.newline, |
|
439 | self.max_width, self.newline.encode(), | |
437 | singleton_pprinters=self.singleton_printers, |
|
440 | singleton_pprinters=self.singleton_printers, | |
438 | type_pprinters=self.type_printers, |
|
441 | type_pprinters=self.type_printers, | |
439 | deferred_pprinters=self.deferred_printers) |
|
442 | deferred_pprinters=self.deferred_printers) | |
440 | printer.pretty(obj) |
|
443 | printer.pretty(obj) | |
441 | printer.flush() |
|
444 | printer.flush() | |
442 | return stream.getvalue() |
|
445 | return stream.getvalue() | |
443 |
|
446 | |||
444 |
|
447 | |||
445 | class HTMLFormatter(BaseFormatter): |
|
448 | class HTMLFormatter(BaseFormatter): | |
446 | """An HTML formatter. |
|
449 | """An HTML formatter. | |
447 |
|
450 | |||
448 | To define the callables that compute the HTML representation of your |
|
451 | To define the callables that compute the HTML representation of your | |
449 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
452 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
450 | or :meth:`for_type_by_name` methods to register functions that handle |
|
453 | or :meth:`for_type_by_name` methods to register functions that handle | |
451 | this. |
|
454 | this. | |
452 |
|
455 | |||
453 | The return value of this formatter should be a valid HTML snippet that |
|
456 | The return value of this formatter should be a valid HTML snippet that | |
454 | could be injected into an existing DOM. It should *not* include the |
|
457 | could be injected into an existing DOM. It should *not* include the | |
455 | ```<html>`` or ```<body>`` tags. |
|
458 | ```<html>`` or ```<body>`` tags. | |
456 | """ |
|
459 | """ | |
457 | format_type = Unicode('text/html') |
|
460 | format_type = Unicode('text/html') | |
458 |
|
461 | |||
459 | print_method = ObjectName('_repr_html_') |
|
462 | print_method = ObjectName('_repr_html_') | |
460 |
|
463 | |||
461 |
|
464 | |||
462 | class SVGFormatter(BaseFormatter): |
|
465 | class SVGFormatter(BaseFormatter): | |
463 | """An SVG formatter. |
|
466 | """An SVG formatter. | |
464 |
|
467 | |||
465 | To define the callables that compute the SVG representation of your |
|
468 | To define the callables that compute the SVG representation of your | |
466 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
469 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
467 | or :meth:`for_type_by_name` methods to register functions that handle |
|
470 | or :meth:`for_type_by_name` methods to register functions that handle | |
468 | this. |
|
471 | this. | |
469 |
|
472 | |||
470 | The return value of this formatter should be valid SVG enclosed in |
|
473 | The return value of this formatter should be valid SVG enclosed in | |
471 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
474 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
472 | *not* include the ```<html>`` or ```<body>`` tags. |
|
475 | *not* include the ```<html>`` or ```<body>`` tags. | |
473 | """ |
|
476 | """ | |
474 | format_type = Unicode('image/svg+xml') |
|
477 | format_type = Unicode('image/svg+xml') | |
475 |
|
478 | |||
476 | print_method = ObjectName('_repr_svg_') |
|
479 | print_method = ObjectName('_repr_svg_') | |
477 |
|
480 | |||
478 |
|
481 | |||
479 | class PNGFormatter(BaseFormatter): |
|
482 | class PNGFormatter(BaseFormatter): | |
480 | """A PNG formatter. |
|
483 | """A PNG formatter. | |
481 |
|
484 | |||
482 | To define the callables that compute the PNG representation of your |
|
485 | To define the callables that compute the PNG representation of your | |
483 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
486 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
484 | or :meth:`for_type_by_name` methods to register functions that handle |
|
487 | or :meth:`for_type_by_name` methods to register functions that handle | |
485 | this. |
|
488 | this. | |
486 |
|
489 | |||
487 | The return value of this formatter should be raw PNG data, *not* |
|
490 | The return value of this formatter should be raw PNG data, *not* | |
488 | base64 encoded. |
|
491 | base64 encoded. | |
489 | """ |
|
492 | """ | |
490 | format_type = Unicode('image/png') |
|
493 | format_type = Unicode('image/png') | |
491 |
|
494 | |||
492 | print_method = ObjectName('_repr_png_') |
|
495 | print_method = ObjectName('_repr_png_') | |
493 |
|
496 | |||
494 |
|
497 | |||
495 | class LatexFormatter(BaseFormatter): |
|
498 | class LatexFormatter(BaseFormatter): | |
496 | """A LaTeX formatter. |
|
499 | """A LaTeX formatter. | |
497 |
|
500 | |||
498 | To define the callables that compute the LaTeX representation of your |
|
501 | To define the callables that compute the LaTeX representation of your | |
499 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
502 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
500 | or :meth:`for_type_by_name` methods to register functions that handle |
|
503 | or :meth:`for_type_by_name` methods to register functions that handle | |
501 | this. |
|
504 | this. | |
502 |
|
505 | |||
503 | The return value of this formatter should be a valid LaTeX equation, |
|
506 | The return value of this formatter should be a valid LaTeX equation, | |
504 | enclosed in either ```$``` or ```$$```. |
|
507 | enclosed in either ```$``` or ```$$```. | |
505 | """ |
|
508 | """ | |
506 | format_type = Unicode('text/latex') |
|
509 | format_type = Unicode('text/latex') | |
507 |
|
510 | |||
508 | print_method = ObjectName('_repr_latex_') |
|
511 | print_method = ObjectName('_repr_latex_') | |
509 |
|
512 | |||
510 |
|
513 | |||
511 | class JSONFormatter(BaseFormatter): |
|
514 | class JSONFormatter(BaseFormatter): | |
512 | """A JSON string formatter. |
|
515 | """A JSON string formatter. | |
513 |
|
516 | |||
514 | To define the callables that compute the JSON string representation of |
|
517 | To define the callables that compute the JSON string representation of | |
515 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
518 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
516 | or :meth:`for_type_by_name` methods to register functions that handle |
|
519 | or :meth:`for_type_by_name` methods to register functions that handle | |
517 | this. |
|
520 | this. | |
518 |
|
521 | |||
519 | The return value of this formatter should be a valid JSON string. |
|
522 | The return value of this formatter should be a valid JSON string. | |
520 | """ |
|
523 | """ | |
521 | format_type = Unicode('application/json') |
|
524 | format_type = Unicode('application/json') | |
522 |
|
525 | |||
523 | print_method = ObjectName('_repr_json_') |
|
526 | print_method = ObjectName('_repr_json_') | |
524 |
|
527 | |||
525 |
|
528 | |||
526 | class JavascriptFormatter(BaseFormatter): |
|
529 | class JavascriptFormatter(BaseFormatter): | |
527 | """A Javascript formatter. |
|
530 | """A Javascript formatter. | |
528 |
|
531 | |||
529 | To define the callables that compute the Javascript representation of |
|
532 | To define the callables that compute the Javascript representation of | |
530 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
533 | your objects, define a :meth:`_repr_javascript_` method or use the | |
531 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
534 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
532 | that handle this. |
|
535 | that handle this. | |
533 |
|
536 | |||
534 | The return value of this formatter should be valid Javascript code and |
|
537 | The return value of this formatter should be valid Javascript code and | |
535 | should *not* be enclosed in ```<script>``` tags. |
|
538 | should *not* be enclosed in ```<script>``` tags. | |
536 | """ |
|
539 | """ | |
537 | format_type = Unicode('application/javascript') |
|
540 | format_type = Unicode('application/javascript') | |
538 |
|
541 | |||
539 | print_method = ObjectName('_repr_javascript_') |
|
542 | print_method = ObjectName('_repr_javascript_') | |
540 |
|
543 | |||
541 | FormatterABC.register(BaseFormatter) |
|
544 | FormatterABC.register(BaseFormatter) | |
542 | FormatterABC.register(PlainTextFormatter) |
|
545 | FormatterABC.register(PlainTextFormatter) | |
543 | FormatterABC.register(HTMLFormatter) |
|
546 | FormatterABC.register(HTMLFormatter) | |
544 | FormatterABC.register(SVGFormatter) |
|
547 | FormatterABC.register(SVGFormatter) | |
545 | FormatterABC.register(PNGFormatter) |
|
548 | FormatterABC.register(PNGFormatter) | |
546 | FormatterABC.register(LatexFormatter) |
|
549 | FormatterABC.register(LatexFormatter) | |
547 | FormatterABC.register(JSONFormatter) |
|
550 | FormatterABC.register(JSONFormatter) | |
548 | FormatterABC.register(JavascriptFormatter) |
|
551 | FormatterABC.register(JavascriptFormatter) | |
549 |
|
552 | |||
550 |
|
553 | |||
551 | def format_display_data(obj, include=None, exclude=None): |
|
554 | def format_display_data(obj, include=None, exclude=None): | |
552 | """Return a format data dict for an object. |
|
555 | """Return a format data dict for an object. | |
553 |
|
556 | |||
554 | By default all format types will be computed. |
|
557 | By default all format types will be computed. | |
555 |
|
558 | |||
556 | The following MIME types are currently implemented: |
|
559 | The following MIME types are currently implemented: | |
557 |
|
560 | |||
558 | * text/plain |
|
561 | * text/plain | |
559 | * text/html |
|
562 | * text/html | |
560 | * text/latex |
|
563 | * text/latex | |
561 | * application/json |
|
564 | * application/json | |
562 | * image/png |
|
565 | * image/png | |
563 | * immage/svg+xml |
|
566 | * immage/svg+xml | |
564 |
|
567 | |||
565 | Parameters |
|
568 | Parameters | |
566 | ---------- |
|
569 | ---------- | |
567 | obj : object |
|
570 | obj : object | |
568 | The Python object whose format data will be computed. |
|
571 | The Python object whose format data will be computed. | |
569 |
|
572 | |||
570 | Returns |
|
573 | Returns | |
571 | ------- |
|
574 | ------- | |
572 | format_dict : dict |
|
575 | format_dict : dict | |
573 | A dictionary of key/value pairs, one or each format that was |
|
576 | A dictionary of key/value pairs, one or each format that was | |
574 | generated for the object. The keys are the format types, which |
|
577 | generated for the object. The keys are the format types, which | |
575 | will usually be MIME type strings and the values and JSON'able |
|
578 | will usually be MIME type strings and the values and JSON'able | |
576 | data structure containing the raw data for the representation in |
|
579 | data structure containing the raw data for the representation in | |
577 | that format. |
|
580 | that format. | |
578 | include : list or tuple, optional |
|
581 | include : list or tuple, optional | |
579 | A list of format type strings (MIME types) to include in the |
|
582 | A list of format type strings (MIME types) to include in the | |
580 | format data dict. If this is set *only* the format types included |
|
583 | format data dict. If this is set *only* the format types included | |
581 | in this list will be computed. |
|
584 | in this list will be computed. | |
582 | exclude : list or tuple, optional |
|
585 | exclude : list or tuple, optional | |
583 | A list of format type string (MIME types) to exclue in the format |
|
586 | A list of format type string (MIME types) to exclue in the format | |
584 | data dict. If this is set all format types will be computed, |
|
587 | data dict. If this is set all format types will be computed, | |
585 | except for those included in this argument. |
|
588 | except for those included in this argument. | |
586 | """ |
|
589 | """ | |
587 | from IPython.core.interactiveshell import InteractiveShell |
|
590 | from IPython.core.interactiveshell import InteractiveShell | |
588 |
|
591 | |||
589 | InteractiveShell.instance().display_formatter.format( |
|
592 | InteractiveShell.instance().display_formatter.format( | |
590 | obj, |
|
593 | obj, | |
591 | include, |
|
594 | include, | |
592 | exclude |
|
595 | exclude | |
593 | ) |
|
596 | ) |
@@ -1,116 +1,124 b'' | |||||
1 | """Tests for the key interactiveshell module. |
|
1 | """Tests for the key interactiveshell module. | |
2 |
|
2 | |||
3 | Historically the main classes in interactiveshell have been under-tested. This |
|
3 | Historically the main classes in interactiveshell have been under-tested. This | |
4 | module should grow as many single-method tests as possible to trap many of the |
|
4 | module should grow as many single-method tests as possible to trap many of the | |
5 | recurring bugs we seem to encounter with high-level interaction. |
|
5 | recurring bugs we seem to encounter with high-level interaction. | |
6 |
|
6 | |||
7 | Authors |
|
7 | Authors | |
8 | ------- |
|
8 | ------- | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 | """ |
|
10 | """ | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2011 The IPython Development Team |
|
12 | # Copyright (C) 2011 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # stdlib |
|
21 | # stdlib | |
22 | import unittest |
|
22 | import unittest | |
23 | from cStringIO import StringIO |
|
23 | from cStringIO import StringIO | |
24 |
|
24 | |||
25 | from IPython.testing import decorators as dec |
|
25 | from IPython.testing import decorators as dec | |
26 | from IPython.utils import io |
|
26 | from IPython.utils import io | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Tests |
|
29 | # Tests | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | class InteractiveShellTestCase(unittest.TestCase): |
|
32 | class InteractiveShellTestCase(unittest.TestCase): | |
33 | def test_naked_string_cells(self): |
|
33 | def test_naked_string_cells(self): | |
34 | """Test that cells with only naked strings are fully executed""" |
|
34 | """Test that cells with only naked strings are fully executed""" | |
35 | ip = get_ipython() |
|
35 | ip = get_ipython() | |
36 | # First, single-line inputs |
|
36 | # First, single-line inputs | |
37 | ip.run_cell('"a"\n') |
|
37 | ip.run_cell('"a"\n') | |
38 | self.assertEquals(ip.user_ns['_'], 'a') |
|
38 | self.assertEquals(ip.user_ns['_'], 'a') | |
39 | # And also multi-line cells |
|
39 | # And also multi-line cells | |
40 | ip.run_cell('"""a\nb"""\n') |
|
40 | ip.run_cell('"""a\nb"""\n') | |
41 | self.assertEquals(ip.user_ns['_'], 'a\nb') |
|
41 | self.assertEquals(ip.user_ns['_'], 'a\nb') | |
42 |
|
42 | |||
43 | def test_run_empty_cell(self): |
|
43 | def test_run_empty_cell(self): | |
44 | """Just make sure we don't get a horrible error with a blank |
|
44 | """Just make sure we don't get a horrible error with a blank | |
45 | cell of input. Yes, I did overlook that.""" |
|
45 | cell of input. Yes, I did overlook that.""" | |
46 | ip = get_ipython() |
|
46 | ip = get_ipython() | |
47 | old_xc = ip.execution_count |
|
47 | old_xc = ip.execution_count | |
48 | ip.run_cell('') |
|
48 | ip.run_cell('') | |
49 | self.assertEquals(ip.execution_count, old_xc) |
|
49 | self.assertEquals(ip.execution_count, old_xc) | |
50 |
|
50 | |||
51 | def test_run_cell_multiline(self): |
|
51 | def test_run_cell_multiline(self): | |
52 | """Multi-block, multi-line cells must execute correctly. |
|
52 | """Multi-block, multi-line cells must execute correctly. | |
53 | """ |
|
53 | """ | |
54 | ip = get_ipython() |
|
54 | ip = get_ipython() | |
55 | src = '\n'.join(["x=1", |
|
55 | src = '\n'.join(["x=1", | |
56 | "y=2", |
|
56 | "y=2", | |
57 | "if 1:", |
|
57 | "if 1:", | |
58 | " x += 1", |
|
58 | " x += 1", | |
59 | " y += 1",]) |
|
59 | " y += 1",]) | |
60 | ip.run_cell(src) |
|
60 | ip.run_cell(src) | |
61 | self.assertEquals(ip.user_ns['x'], 2) |
|
61 | self.assertEquals(ip.user_ns['x'], 2) | |
62 | self.assertEquals(ip.user_ns['y'], 3) |
|
62 | self.assertEquals(ip.user_ns['y'], 3) | |
63 |
|
63 | |||
64 | def test_multiline_string_cells(self): |
|
64 | def test_multiline_string_cells(self): | |
65 | "Code sprinkled with multiline strings should execute (GH-306)" |
|
65 | "Code sprinkled with multiline strings should execute (GH-306)" | |
66 | ip = get_ipython() |
|
66 | ip = get_ipython() | |
67 | ip.run_cell('tmp=0') |
|
67 | ip.run_cell('tmp=0') | |
68 | self.assertEquals(ip.user_ns['tmp'], 0) |
|
68 | self.assertEquals(ip.user_ns['tmp'], 0) | |
69 | ip.run_cell('tmp=1;"""a\nb"""\n') |
|
69 | ip.run_cell('tmp=1;"""a\nb"""\n') | |
70 | self.assertEquals(ip.user_ns['tmp'], 1) |
|
70 | self.assertEquals(ip.user_ns['tmp'], 1) | |
71 |
|
71 | |||
72 | def test_dont_cache_with_semicolon(self): |
|
72 | def test_dont_cache_with_semicolon(self): | |
73 | "Ending a line with semicolon should not cache the returned object (GH-307)" |
|
73 | "Ending a line with semicolon should not cache the returned object (GH-307)" | |
74 | ip = get_ipython() |
|
74 | ip = get_ipython() | |
75 | oldlen = len(ip.user_ns['Out']) |
|
75 | oldlen = len(ip.user_ns['Out']) | |
76 | a = ip.run_cell('1;') |
|
76 | a = ip.run_cell('1;') | |
77 | newlen = len(ip.user_ns['Out']) |
|
77 | newlen = len(ip.user_ns['Out']) | |
78 | self.assertEquals(oldlen, newlen) |
|
78 | self.assertEquals(oldlen, newlen) | |
79 | #also test the default caching behavior |
|
79 | #also test the default caching behavior | |
80 | ip.run_cell('1') |
|
80 | ip.run_cell('1') | |
81 | newlen = len(ip.user_ns['Out']) |
|
81 | newlen = len(ip.user_ns['Out']) | |
82 | self.assertEquals(oldlen+1, newlen) |
|
82 | self.assertEquals(oldlen+1, newlen) | |
83 |
|
83 | |||
84 | def test_In_variable(self): |
|
84 | def test_In_variable(self): | |
85 | "Verify that In variable grows with user input (GH-284)" |
|
85 | "Verify that In variable grows with user input (GH-284)" | |
86 | ip = get_ipython() |
|
86 | ip = get_ipython() | |
87 | oldlen = len(ip.user_ns['In']) |
|
87 | oldlen = len(ip.user_ns['In']) | |
88 | ip.run_cell('1;') |
|
88 | ip.run_cell('1;') | |
89 | newlen = len(ip.user_ns['In']) |
|
89 | newlen = len(ip.user_ns['In']) | |
90 | self.assertEquals(oldlen+1, newlen) |
|
90 | self.assertEquals(oldlen+1, newlen) | |
91 | self.assertEquals(ip.user_ns['In'][-1],'1;') |
|
91 | self.assertEquals(ip.user_ns['In'][-1],'1;') | |
92 |
|
92 | |||
93 | def test_magic_names_in_string(self): |
|
93 | def test_magic_names_in_string(self): | |
94 | ip = get_ipython() |
|
94 | ip = get_ipython() | |
95 | ip.run_cell('a = """\n%exit\n"""') |
|
95 | ip.run_cell('a = """\n%exit\n"""') | |
96 | self.assertEquals(ip.user_ns['a'], '\n%exit\n') |
|
96 | self.assertEquals(ip.user_ns['a'], '\n%exit\n') | |
97 |
|
97 | |||
98 | def test_alias_crash(self): |
|
98 | def test_alias_crash(self): | |
99 | """Errors in prefilter can't crash IPython""" |
|
99 | """Errors in prefilter can't crash IPython""" | |
100 | ip = get_ipython() |
|
100 | ip = get_ipython() | |
101 | ip.run_cell('%alias parts echo first %s second %s') |
|
101 | ip.run_cell('%alias parts echo first %s second %s') | |
102 | # capture stderr: |
|
102 | # capture stderr: | |
103 | save_err = io.stderr |
|
103 | save_err = io.stderr | |
104 | io.stderr = StringIO() |
|
104 | io.stderr = StringIO() | |
105 | ip.run_cell('parts 1') |
|
105 | ip.run_cell('parts 1') | |
106 | err = io.stderr.getvalue() |
|
106 | err = io.stderr.getvalue() | |
107 | io.stderr = save_err |
|
107 | io.stderr = save_err | |
108 | self.assertEquals(err.split(':')[0], 'ERROR') |
|
108 | self.assertEquals(err.split(':')[0], 'ERROR') | |
109 |
|
109 | |||
110 | def test_trailing_newline(self): |
|
110 | def test_trailing_newline(self): | |
111 | """test that running !(command) does not raise a SyntaxError""" |
|
111 | """test that running !(command) does not raise a SyntaxError""" | |
112 | ip = get_ipython() |
|
112 | ip = get_ipython() | |
113 | ip.run_cell('!(true)\n', False) |
|
113 | ip.run_cell('!(true)\n', False) | |
114 | ip.run_cell('!(true)\n\n\n', False) |
|
114 | ip.run_cell('!(true)\n\n\n', False) | |
115 |
|
115 | |||
116 |
|
116 | def test_gh_597(self): | ||
|
117 | """Pretty-printing lists of objects with non-ascii reprs may cause | |||
|
118 | problems.""" | |||
|
119 | class Spam(object): | |||
|
120 | def __repr__(self): | |||
|
121 | return "\xe9"*50 | |||
|
122 | import IPython.core.formatters | |||
|
123 | f = IPython.core.formatters.PlainTextFormatter() | |||
|
124 | f([Spam(),Spam()]) |
General Comments 0
You need to be logged in to leave comments.
Login now