##// END OF EJS Templates
Renaming the special methods of the formatters....
Brian Granger -
Show More
@@ -0,0 +1,26 b''
1 """Code that shows off the IPython display logic.
2 """
3
4 from IPython.core.display import (
5 display, display_pretty, display_html,
6 display_svg, display_json
7 )
8
9 class Circle(object):
10
11 def __init__(self, radius):
12 self.radius = radius
13
14 def _repr_pretty_(self, p, cycle):
15 p.text(u"\u25CB")
16
17 __pretty__ = _repr_pretty_
18
19 def _repr_html_(self):
20 return "<h1>Cirle: radius=%s</h1>" % self.radius
21
22 def _repr_svg_(self):
23 return """<svg>
24 <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
25 </svg>"""
26
@@ -1,122 +1,130 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2010 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Main functions
22 22 #-----------------------------------------------------------------------------
23 23
24 24 def display(*objs, **kwargs):
25 25 """Display a Python object in all frontends.
26 26
27 27 By default all representations will be computed and sent to the frontends.
28 28 Frontends can decide which representation is used and how.
29 29
30 30 Parameters
31 31 ----------
32 32 objs : tuple of objects
33 33 The Python objects to display.
34 34 include : list or tuple, optional
35 35 A list of format type strings (MIME types) to include in the
36 36 format data dict. If this is set *only* the format types included
37 37 in this list will be computed.
38 38 exclude : list or tuple, optional
39 39 A list of format type string (MIME types) to exclue in the format
40 40 data dict. If this is set all format types will be computed,
41 41 except for those included in this argument.
42 42 """
43 43 include = kwargs.get('include')
44 44 exclude = kwargs.get('exclude')
45 45
46 46 from IPython.core.interactiveshell import InteractiveShell
47 47 inst = InteractiveShell.instance()
48 48 format = inst.display_formatter.format
49 49 publish = inst.display_pub.publish
50 50
51 51 for obj in objs:
52 52 format_dict = format(obj, include=include, exclude=exclude)
53 53 publish('IPython.core.display.display', format_dict)
54 54
55 55
56 56 def display_pretty(*objs):
57 57 """Display the pretty (default) representation of an object.
58 58
59 59 Parameters
60 60 ----------
61 61 objs : tuple of objects
62 62 The Python objects to display.
63 63 """
64 64 display(*objs, include=['text/plain'])
65 65
66 66
67 67 def display_html(*objs):
68 68 """Display the HTML representation of an object.
69 69
70 70 Parameters
71 71 ----------
72 72 objs : tuple of objects
73 73 The Python objects to display.
74 74 """
75 75 display(*objs, include=['text/plain','text/html'])
76 76
77 77
78 78 def display_svg(*objs):
79 79 """Display the SVG representation of an object.
80 80
81 81 Parameters
82 82 ----------
83 83 objs : tuple of objects
84 84 The Python objects to display.
85 85 """
86 86 display(*objs, include=['text/plain','image/svg+xml'])
87 87
88 88
89 89 def display_png(*objs):
90 90 """Display the PNG representation of an object.
91 91
92 92 Parameters
93 93 ----------
94 94 objs : tuple of objects
95 95 The Python objects to display.
96 96 """
97 97 display(*objs, include=['text/plain','image/png'])
98 98
99 99
100 100 def display_latex(*objs):
101 101 """Display the LaTeX representation of an object.
102 102
103 103 Parameters
104 104 ----------
105 105 objs : tuple of objects
106 106 The Python objects to display.
107 107 """
108 108 display(*objs, include=['text/plain','text/latex'])
109 109
110 110
111 111 def display_json(*objs):
112 112 """Display the JSON representation of an object.
113 113
114 114 Parameters
115 115 ----------
116 116 objs : tuple of objects
117 117 The Python objects to display.
118 118 """
119 119 display(*objs, include=['text/plain','application/json'])
120 120
121 121
122 def display_javascript(*objs):
123 """Display the Javascript representation of an object.
122 124
125 Parameters
126 ----------
127 objs : tuple of objects
128 The Python objects to display.
129 """
130 display(*objs, include=['text/plain','application/javascript'])
@@ -1,557 +1,576 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4
5 5 Authors:
6 6
7 7 * Robert Kern
8 8 * Brian Granger
9 9 """
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (c) 2010, IPython Development Team.
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 # Stdlib imports
23 23 import abc
24 24 import sys
25 25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
26 26 from StringIO import StringIO
27 27
28 28 # Our own imports
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.lib import pretty
31 31 from IPython.utils.traitlets import Bool, Dict, Int, Str, CStr
32 32
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # The main DisplayFormatter class
36 36 #-----------------------------------------------------------------------------
37 37
38 38
39 39 class DisplayFormatter(Configurable):
40 40
41 41 # When set to true only the default plain text formatter will be used.
42 42 plain_text_only = Bool(False, config=True)
43 43
44 44 # A dict of formatter whose keys are format types (MIME types) and whose
45 45 # values are subclasses of BaseFormatter.
46 46 formatters = Dict(config=True)
47 47 def _formatters_default(self):
48 48 """Activate the default formatters."""
49 49 formatter_classes = [
50 50 PlainTextFormatter,
51 51 HTMLFormatter,
52 52 SVGFormatter,
53 53 PNGFormatter,
54 54 LatexFormatter,
55 JSONFormatter
55 JSONFormatter,
56 JavascriptFormatter
56 57 ]
57 58 d = {}
58 59 for cls in formatter_classes:
59 60 f = cls(config=self.config)
60 61 d[f.format_type] = f
61 62 return d
62 63
63 64 def format(self, obj, include=None, exclude=None):
64 65 """Return a format data dict for an object.
65 66
66 67 By default all format types will be computed.
67 68
68 69 The following MIME types are currently implemented:
69 70
70 71 * text/plain
71 72 * text/html
72 73 * text/latex
73 74 * application/json
74 75 * image/png
75 76 * immage/svg+xml
76 77
77 78 Parameters
78 79 ----------
79 80 obj : object
80 81 The Python object whose format data will be computed.
81 82 include : list or tuple, optional
82 83 A list of format type strings (MIME types) to include in the
83 84 format data dict. If this is set *only* the format types included
84 85 in this list will be computed.
85 86 exclude : list or tuple, optional
86 87 A list of format type string (MIME types) to exclue in the format
87 88 data dict. If this is set all format types will be computed,
88 89 except for those included in this argument.
89 90
90 91 Returns
91 92 -------
92 93 format_dict : dict
93 94 A dictionary of key/value pairs, one or each format that was
94 95 generated for the object. The keys are the format types, which
95 96 will usually be MIME type strings and the values and JSON'able
96 97 data structure containing the raw data for the representation in
97 98 that format.
98 99 """
99 100 format_dict = {}
100 101
101 102 # If plain text only is active
102 103 if self.plain_text_only:
103 104 formatter = self.formatters['text/plain']
104 105 try:
105 106 data = formatter(obj)
106 107 except:
107 108 # FIXME: log the exception
108 109 raise
109 110 if data is not None:
110 111 format_dict['text/plain'] = data
111 112 return format_dict
112 113
113 114 for format_type, formatter in self.formatters.items():
114 115 if include is not None:
115 116 if format_type not in include:
116 117 continue
117 118 if exclude is not None:
118 119 if format_type in exclude:
119 120 continue
120 121 try:
121 122 data = formatter(obj)
122 123 except:
123 124 # FIXME: log the exception
124 125 raise
125 126 if data is not None:
126 127 format_dict[format_type] = data
127 128 return format_dict
128 129
129 130 @property
130 131 def format_types(self):
131 132 """Return the format types (MIME types) of the active formatters."""
132 133 return self.formatters.keys()
133 134
134 135
135 136 #-----------------------------------------------------------------------------
136 137 # Formatters for specific format types (text, html, svg, etc.)
137 138 #-----------------------------------------------------------------------------
138 139
139 140
140 141 class FormatterABC(object):
141 142 """ Abstract base class for Formatters.
142 143
143 144 A formatter is a callable class that is responsible for computing the
144 145 raw format data for a particular format type (MIME type). For example,
145 146 an HTML formatter would have a format type of `text/html` and would return
146 147 the HTML representation of the object when called.
147 148 """
148 149 __metaclass__ = abc.ABCMeta
149 150
150 151 # The format type of the data returned, usually a MIME type.
151 152 format_type = 'text/plain'
152 153
153 154 # Is the formatter enabled...
154 155 enabled = True
155 156
156 157 @abc.abstractmethod
157 158 def __call__(self, obj):
158 159 """Return a JSON'able representation of the object.
159 160
160 161 If the object cannot be formatted by this formatter, then return None
161 162 """
162 163 try:
163 164 return repr(obj)
164 165 except TypeError:
165 166 return None
166 167
167 168
168 169 class BaseFormatter(Configurable):
169 170 """A base formatter class that is configurable.
170 171
171 172 This formatter should usually be used as the base class of all formatters.
172 173 It is a traited :class:`Configurable` class and includes an extensible
173 174 API for users to determine how their objects are formatted. The following
174 175 logic is used to find a function to format an given object.
175 176
176 177 1. The object is introspected to see if it has a method with the name
177 178 :attr:`print_method`. If is does, that object is passed to that method
178 179 for formatting.
179 180 2. If no print method is found, three internal dictionaries are consulted
180 181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
181 182 and :attr:`deferred_printers`.
182 183
183 184 Users should use these dictionaries to register functions that will be
184 185 used to compute the format data for their objects (if those objects don't
185 186 have the special print methods). The easiest way of using these
186 187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
187 188 methods.
188 189
189 190 If no function/callable is found to compute the format data, ``None`` is
190 191 returned and this format type is not used.
191 192 """
192 193
193 194 format_type = Str('text/plain')
194 195
195 196 enabled = Bool(True, config=True)
196 197
197 198 print_method = Str('__repr__')
198 199
199 200 # The singleton printers.
200 201 # Maps the IDs of the builtin singleton objects to the format functions.
201 202 singleton_printers = Dict(config=True)
202 203 def _singleton_printers_default(self):
203 204 return {}
204 205
205 206 # The type-specific printers.
206 207 # Map type objects to the format functions.
207 208 type_printers = Dict(config=True)
208 209 def _type_printers_default(self):
209 210 return {}
210 211
211 212 # The deferred-import type-specific printers.
212 213 # Map (modulename, classname) pairs to the format functions.
213 214 deferred_printers = Dict(config=True)
214 215 def _deferred_printers_default(self):
215 216 return {}
216 217
217 218 def __call__(self, obj):
218 219 """Compute the format for an object."""
219 220 if self.enabled:
220 221 obj_id = id(obj)
221 222 try:
222 223 obj_class = getattr(obj, '__class__', None) or type(obj)
223 if hasattr(obj_class, self.print_method):
224 printer = getattr(obj_class, self.print_method)
225 return printer(obj)
224 # First try to find registered singleton printers for the type.
226 225 try:
227 226 printer = self.singleton_printers[obj_id]
228 227 except (TypeError, KeyError):
229 228 pass
230 229 else:
231 230 return printer(obj)
231 # Next look for type_printers.
232 232 for cls in pretty._get_mro(obj_class):
233 233 if cls in self.type_printers:
234 234 return self.type_printers[cls](obj)
235 235 else:
236 236 printer = self._in_deferred_types(cls)
237 237 if printer is not None:
238 238 return printer(obj)
239 # Finally look for special method names.
240 if hasattr(obj_class, self.print_method):
241 printer = getattr(obj_class, self.print_method)
242 return printer(obj)
239 243 return None
240 244 except Exception:
241 245 pass
242 246 else:
243 247 return None
244 248
245 249 def for_type(self, typ, func):
246 250 """Add a format function for a given type.
247 251
248 252 Parameters
249 253 -----------
250 254 typ : class
251 255 The class of the object that will be formatted using `func`.
252 256 func : callable
253 257 The callable that will be called to compute the format data. The
254 258 call signature of this function is simple, it must take the
255 259 object to be formatted and return the raw data for the given
256 260 format. Subclasses may use a different call signature for the
257 261 `func` argument.
258 262 """
259 263 oldfunc = self.type_printers.get(typ, None)
260 264 if func is not None:
261 265 # To support easy restoration of old printers, we need to ignore
262 266 # Nones.
263 267 self.type_printers[typ] = func
264 268 return oldfunc
265 269
266 270 def for_type_by_name(self, type_module, type_name, func):
267 271 """Add a format function for a type specified by the full dotted
268 272 module and name of the type, rather than the type of the object.
269 273
270 274 Parameters
271 275 ----------
272 276 type_module : str
273 277 The full dotted name of the module the type is defined in, like
274 278 ``numpy``.
275 279 type_name : str
276 280 The name of the type (the class name), like ``dtype``
277 281 func : callable
278 282 The callable that will be called to compute the format data. The
279 283 call signature of this function is simple, it must take the
280 284 object to be formatted and return the raw data for the given
281 285 format. Subclasses may use a different call signature for the
282 286 `func` argument.
283 287 """
284 288 key = (type_module, type_name)
285 289 oldfunc = self.deferred_printers.get(key, None)
286 290 if func is not None:
287 291 # To support easy restoration of old printers, we need to ignore
288 292 # Nones.
289 293 self.deferred_printers[key] = func
290 294 return oldfunc
291 295
292 296 def _in_deferred_types(self, cls):
293 297 """
294 298 Check if the given class is specified in the deferred type registry.
295 299
296 300 Returns the printer from the registry if it exists, and None if the
297 301 class is not in the registry. Successful matches will be moved to the
298 302 regular type registry for future use.
299 303 """
300 304 mod = getattr(cls, '__module__', None)
301 305 name = getattr(cls, '__name__', None)
302 306 key = (mod, name)
303 307 printer = None
304 308 if key in self.deferred_printers:
305 309 # Move the printer over to the regular registry.
306 310 printer = self.deferred_printers.pop(key)
307 311 self.type_printers[cls] = printer
308 312 return printer
309 313
310 314
311 315 class PlainTextFormatter(BaseFormatter):
312 316 """The default pretty-printer.
313 317
314 318 This uses :mod:`IPython.external.pretty` to compute the format data of
315 319 the object. If the object cannot be pretty printed, :func:`repr` is used.
316 320 See the documentation of :mod:`IPython.external.pretty` for details on
317 321 how to write pretty printers. Here is a simple example::
318 322
319 323 def dtype_pprinter(obj, p, cycle):
320 324 if cycle:
321 325 return p.text('dtype(...)')
322 326 if hasattr(obj, 'fields'):
323 327 if obj.fields is None:
324 328 p.text(repr(obj))
325 329 else:
326 330 p.begin_group(7, 'dtype([')
327 331 for i, field in enumerate(obj.descr):
328 332 if i > 0:
329 333 p.text(',')
330 334 p.breakable()
331 335 p.pretty(field)
332 336 p.end_group(7, '])')
333 337 """
334 338
335 339 # The format type of data returned.
336 340 format_type = Str('text/plain')
337 341
338 342 # This subclass ignores this attribute as it always need to return
339 343 # something.
340 344 enabled = Bool(True, config=False)
341 345
342 346 # Look for a __pretty__ methods to use for pretty printing.
343 347 print_method = Str('__pretty__')
344 348
345 349 # Whether to pretty-print or not.
346 350 pprint = Bool(True, config=True)
347 351
348 352 # Whether to be verbose or not.
349 353 verbose = Bool(False, config=True)
350 354
351 355 # The maximum width.
352 356 max_width = Int(79, config=True)
353 357
354 358 # The newline character.
355 359 newline = Str('\n', config=True)
356 360
357 361 # format-string for pprinting floats
358 362 float_format = Str('%r')
359 363 # setter for float precision, either int or direct format-string
360 364 float_precision = CStr('', config=True)
361 365
362 366 def _float_precision_changed(self, name, old, new):
363 367 """float_precision changed, set float_format accordingly.
364 368
365 369 float_precision can be set by int or str.
366 370 This will set float_format, after interpreting input.
367 371 If numpy has been imported, numpy print precision will also be set.
368 372
369 373 integer `n` sets format to '%.nf', otherwise, format set directly.
370 374
371 375 An empty string returns to defaults (repr for float, 8 for numpy).
372 376
373 377 This parameter can be set via the '%precision' magic.
374 378 """
375 379
376 380 if '%' in new:
377 381 # got explicit format string
378 382 fmt = new
379 383 try:
380 384 fmt%3.14159
381 385 except Exception:
382 386 raise ValueError("Precision must be int or format string, not %r"%new)
383 387 elif new:
384 388 # otherwise, should be an int
385 389 try:
386 390 i = int(new)
387 391 assert i >= 0
388 392 except ValueError:
389 393 raise ValueError("Precision must be int or format string, not %r"%new)
390 394 except AssertionError:
391 395 raise ValueError("int precision must be non-negative, not %r"%i)
392 396
393 397 fmt = '%%.%if'%i
394 398 if 'numpy' in sys.modules:
395 399 # set numpy precision if it has been imported
396 400 import numpy
397 401 numpy.set_printoptions(precision=i)
398 402 else:
399 403 # default back to repr
400 404 fmt = '%r'
401 405 if 'numpy' in sys.modules:
402 406 import numpy
403 407 # numpy default is 8
404 408 numpy.set_printoptions(precision=8)
405 409 self.float_format = fmt
406 410
407 411 # Use the default pretty printers from IPython.external.pretty.
408 412 def _singleton_printers_default(self):
409 413 return pretty._singleton_pprinters.copy()
410 414
411 415 def _type_printers_default(self):
412 416 d = pretty._type_pprinters.copy()
413 417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
414 418 return d
415 419
416 420 def _deferred_printers_default(self):
417 421 return pretty._deferred_type_pprinters.copy()
418 422
419 423 #### FormatterABC interface ####
420 424
421 425 def __call__(self, obj):
422 426 """Compute the pretty representation of the object."""
423 427 if not self.pprint:
424 428 try:
425 429 return repr(obj)
426 430 except TypeError:
427 431 return ''
428 432 else:
429 433 # This uses use StringIO, as cStringIO doesn't handle unicode.
430 434 stream = StringIO()
431 435 printer = pretty.RepresentationPrinter(stream, self.verbose,
432 436 self.max_width, self.newline,
433 437 singleton_pprinters=self.singleton_printers,
434 438 type_pprinters=self.type_printers,
435 439 deferred_pprinters=self.deferred_printers)
436 440 printer.pretty(obj)
437 441 printer.flush()
438 442 return stream.getvalue()
439 443
440 444
441 445 class HTMLFormatter(BaseFormatter):
442 446 """An HTML formatter.
443 447
444 448 To define the callables that compute the HTML representation of your
445 objects, define a :meth:`__html__` method or use the :meth:`for_type`
449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
446 450 or :meth:`for_type_by_name` methods to register functions that handle
447 451 this.
448 452 """
449 453 format_type = Str('text/html')
450 454
451 print_method = Str('__html__')
455 print_method = Str('_repr_html_')
452 456
453 457
454 458 class SVGFormatter(BaseFormatter):
455 459 """An SVG formatter.
456 460
457 461 To define the callables that compute the SVG representation of your
458 objects, define a :meth:`__svg__` method or use the :meth:`for_type`
462 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
459 463 or :meth:`for_type_by_name` methods to register functions that handle
460 464 this.
461 465 """
462 466 format_type = Str('image/svg+xml')
463 467
464 print_method = Str('__svg__')
468 print_method = Str('_repr_svg_')
465 469
466 470
467 471 class PNGFormatter(BaseFormatter):
468 472 """A PNG formatter.
469 473
470 474 To define the callables that compute the PNG representation of your
471 objects, define a :meth:`__png__` method or use the :meth:`for_type`
475 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
472 476 or :meth:`for_type_by_name` methods to register functions that handle
473 this. The raw data should be the base64 encoded raw png data.
477 this.
478
479 The raw data should be the base64 encoded raw png data.
474 480 """
475 481 format_type = Str('image/png')
476 482
477 print_method = Str('__png__')
483 print_method = Str('_repr_png_')
478 484
479 485
480 486 class LatexFormatter(BaseFormatter):
481 487 """A LaTeX formatter.
482 488
483 489 To define the callables that compute the LaTeX representation of your
484 objects, define a :meth:`__latex__` method or use the :meth:`for_type`
490 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
485 491 or :meth:`for_type_by_name` methods to register functions that handle
486 492 this.
487 493 """
488 494 format_type = Str('text/latex')
489 495
490 print_method = Str('__latex__')
496 print_method = Str('_repr_latex_')
491 497
492 498
493 499 class JSONFormatter(BaseFormatter):
494 500 """A JSON string formatter.
495 501
496 502 To define the callables that compute the JSON string representation of
497 your objects, define a :meth:`__json__` method or use the :meth:`for_type`
503 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
498 504 or :meth:`for_type_by_name` methods to register functions that handle
499 505 this.
500 506 """
501 507 format_type = Str('application/json')
502 508
503 print_method = Str('__json__')
509 print_method = Str('_repr_json_')
510
511
512 class JavascriptFormatter(BaseFormatter):
513 """A Javascript formatter.
514
515 To define the callables that compute the Javascript representation of
516 your objects, define a :meth:`_repr_javascript_` method or use the
517 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
518 that handle this.
519 """
520 format_type = Str('application/javascript')
504 521
522 print_method = Str('_repr_javascript_')
505 523
506 524 FormatterABC.register(BaseFormatter)
507 525 FormatterABC.register(PlainTextFormatter)
508 526 FormatterABC.register(HTMLFormatter)
509 527 FormatterABC.register(SVGFormatter)
510 528 FormatterABC.register(PNGFormatter)
511 529 FormatterABC.register(LatexFormatter)
512 530 FormatterABC.register(JSONFormatter)
531 FormatterABC.register(JavascriptFormatter)
513 532
514 533
515 534 def format_display_data(obj, include=None, exclude=None):
516 535 """Return a format data dict for an object.
517 536
518 537 By default all format types will be computed.
519 538
520 539 The following MIME types are currently implemented:
521 540
522 541 * text/plain
523 542 * text/html
524 543 * text/latex
525 544 * application/json
526 545 * image/png
527 546 * immage/svg+xml
528 547
529 548 Parameters
530 549 ----------
531 550 obj : object
532 551 The Python object whose format data will be computed.
533 552
534 553 Returns
535 554 -------
536 555 format_dict : dict
537 556 A dictionary of key/value pairs, one or each format that was
538 557 generated for the object. The keys are the format types, which
539 558 will usually be MIME type strings and the values and JSON'able
540 559 data structure containing the raw data for the representation in
541 560 that format.
542 561 include : list or tuple, optional
543 562 A list of format type strings (MIME types) to include in the
544 563 format data dict. If this is set *only* the format types included
545 564 in this list will be computed.
546 565 exclude : list or tuple, optional
547 566 A list of format type string (MIME types) to exclue in the format
548 567 data dict. If this is set all format types will be computed,
549 568 except for those included in this argument.
550 569 """
551 570 from IPython.core.interactiveshell import InteractiveShell
552 571
553 572 InteractiveShell.instance().display_formatter.format(
554 573 obj,
555 574 include,
556 575 exclude
557 576 )
@@ -1,509 +1,509 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Usage information for the main IPython applications.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2008-2010 The IPython Development Team
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 #
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import sys
13 13 from IPython.core import release
14 14
15 15 cl_usage = """\
16 16 ipython [options] [files]
17 17
18 18 IPython: an enhanced interactive Python shell.
19 19
20 20 A Python shell with automatic history (input and output), dynamic object
21 21 introspection, easier configuration, command completion, access to the
22 22 system shell and more. IPython can also be embedded in running programs.
23 23
24 24 If invoked with no options, it executes all the files listed in sequence
25 25 and exits, use -i to enter interactive mode after running the files. Files
26 26 ending in .py will be treated as normal Python, but files ending in .ipy
27 27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28 28
29 29 Please note that some of the configuration options are not available at the
30 30 command line, simply because they are not practical here. Look into your
31 31 ipython_config.py configuration file for details on those.
32 32
33 33 This file is typically installed in the IPYTHON_DIR directory. For Linux
34 34 users, this will be $HOME/.config/ipython, and for other users it will be
35 35 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
36 36 Settings\\YourUserName in most instances.
37 37
38 38 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
39 39 you can change its default location by setting any path you want in this
40 40 environment variable.
41 41
42 42 For more information, see the manual available in HTML and PDF in your
43 43 installation, or online at http://ipython.scipy.org.
44 44 """
45 45
46 46 interactive_usage = """
47 47 IPython -- An enhanced Interactive Python
48 48 =========================================
49 49
50 50 IPython offers a combination of convenient shell features, special commands
51 51 and a history mechanism for both input (command history) and output (results
52 52 caching, similar to Mathematica). It is intended to be a fully compatible
53 53 replacement for the standard Python interpreter, while offering vastly
54 54 improved functionality and flexibility.
55 55
56 56 At your system command line, type 'ipython -help' to see the command line
57 57 options available. This document only describes interactive features.
58 58
59 59 Warning: IPython relies on the existence of a global variable called __IP which
60 60 controls the shell itself. If you redefine __IP to anything, bizarre behavior
61 61 will quickly occur.
62 62
63 63 MAIN FEATURES
64 64
65 65 * Access to the standard Python help. As of Python 2.1, a help system is
66 66 available with access to object docstrings and the Python manuals. Simply
67 67 type 'help' (no quotes) to access it.
68 68
69 69 * Magic commands: type %magic for information on the magic subsystem.
70 70
71 71 * System command aliases, via the %alias command or the ipythonrc config file.
72 72
73 73 * Dynamic object information:
74 74
75 75 Typing ?word or word? prints detailed information about an object. If
76 76 certain strings in the object are too long (docstrings, code, etc.) they get
77 77 snipped in the center for brevity.
78 78
79 79 Typing ??word or word?? gives access to the full information without
80 80 snipping long strings. Long strings are sent to the screen through the less
81 81 pager if longer than the screen, printed otherwise.
82 82
83 83 The ?/?? system gives access to the full source code for any object (if
84 84 available), shows function prototypes and other useful information.
85 85
86 86 If you just want to see an object's docstring, type '%pdoc object' (without
87 87 quotes, and without % if you have automagic on).
88 88
89 89 Both %pdoc and ?/?? give you access to documentation even on things which are
90 90 not explicitely defined. Try for example typing {}.get? or after import os,
91 91 type os.path.abspath??. The magic functions %pdef, %source and %file operate
92 92 similarly.
93 93
94 94 * Completion in the local namespace, by typing TAB at the prompt.
95 95
96 96 At any time, hitting tab will complete any available python commands or
97 97 variable names, and show you a list of the possible completions if there's
98 98 no unambiguous one. It will also complete filenames in the current directory.
99 99
100 100 This feature requires the readline and rlcomplete modules, so it won't work
101 101 if your Python lacks readline support (such as under Windows).
102 102
103 103 * Search previous command history in two ways (also requires readline):
104 104
105 105 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
106 106 search through only the history items that match what you've typed so
107 107 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
108 108 normal arrow keys.
109 109
110 110 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
111 111 your history for lines that match what you've typed so far, completing as
112 112 much as it can.
113 113
114 114 * Persistent command history across sessions (readline required).
115 115
116 116 * Logging of input with the ability to save and restore a working session.
117 117
118 118 * System escape with !. Typing !ls will run 'ls' in the current directory.
119 119
120 120 * The reload command does a 'deep' reload of a module: changes made to the
121 121 module since you imported will actually be available without having to exit.
122 122
123 123 * Verbose and colored exception traceback printouts. See the magic xmode and
124 124 xcolor functions for details (just type %magic).
125 125
126 126 * Input caching system:
127 127
128 128 IPython offers numbered prompts (In/Out) with input and output caching. All
129 129 input is saved and can be retrieved as variables (besides the usual arrow
130 130 key recall).
131 131
132 132 The following GLOBAL variables always exist (so don't overwrite them!):
133 133 _i: stores previous input.
134 134 _ii: next previous.
135 135 _iii: next-next previous.
136 136 _ih : a list of all input _ih[n] is the input from line n.
137 137
138 138 Additionally, global variables named _i<n> are dynamically created (<n>
139 139 being the prompt counter), such that _i<n> == _ih[<n>]
140 140
141 141 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
142 142
143 143 You can create macros which contain multiple input lines from this history,
144 144 for later re-execution, with the %macro function.
145 145
146 146 The history function %hist allows you to see any part of your input history
147 147 by printing a range of the _i variables. Note that inputs which contain
148 148 magic functions (%) appear in the history with a prepended comment. This is
149 149 because they aren't really valid Python code, so you can't exec them.
150 150
151 151 * Output caching system:
152 152
153 153 For output that is returned from actions, a system similar to the input
154 154 cache exists but using _ instead of _i. Only actions that produce a result
155 155 (NOT assignments, for example) are cached. If you are familiar with
156 156 Mathematica, IPython's _ variables behave exactly like Mathematica's %
157 157 variables.
158 158
159 159 The following GLOBAL variables always exist (so don't overwrite them!):
160 160 _ (one underscore): previous output.
161 161 __ (two underscores): next previous.
162 162 ___ (three underscores): next-next previous.
163 163
164 164 Global variables named _<n> are dynamically created (<n> being the prompt
165 165 counter), such that the result of output <n> is always available as _<n>.
166 166
167 167 Finally, a global dictionary named _oh exists with entries for all lines
168 168 which generated output.
169 169
170 170 * Directory history:
171 171
172 172 Your history of visited directories is kept in the global list _dh, and the
173 173 magic %cd command can be used to go to any entry in that list.
174 174
175 175 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
176 176
177 177 1. Auto-parentheses
178 178 Callable objects (i.e. functions, methods, etc) can be invoked like
179 179 this (notice the commas between the arguments):
180 180 >>> callable_ob arg1, arg2, arg3
181 181 and the input will be translated to this:
182 182 --> callable_ob(arg1, arg2, arg3)
183 183 You can force auto-parentheses by using '/' as the first character
184 184 of a line. For example:
185 185 >>> /globals # becomes 'globals()'
186 186 Note that the '/' MUST be the first character on the line! This
187 187 won't work:
188 188 >>> print /globals # syntax error
189 189
190 190 In most cases the automatic algorithm should work, so you should
191 191 rarely need to explicitly invoke /. One notable exception is if you
192 192 are trying to call a function with a list of tuples as arguments (the
193 193 parenthesis will confuse IPython):
194 194 In [1]: zip (1,2,3),(4,5,6) # won't work
195 195 but this will work:
196 196 In [2]: /zip (1,2,3),(4,5,6)
197 197 ------> zip ((1,2,3),(4,5,6))
198 198 Out[2]= [(1, 4), (2, 5), (3, 6)]
199 199
200 200 IPython tells you that it has altered your command line by
201 201 displaying the new command line preceded by -->. e.g.:
202 202 In [18]: callable list
203 203 -------> callable (list)
204 204
205 205 2. Auto-Quoting
206 206 You can force auto-quoting of a function's arguments by using ',' as
207 207 the first character of a line. For example:
208 208 >>> ,my_function /home/me # becomes my_function("/home/me")
209 209
210 210 If you use ';' instead, the whole argument is quoted as a single
211 211 string (while ',' splits on whitespace):
212 212 >>> ,my_function a b c # becomes my_function("a","b","c")
213 213 >>> ;my_function a b c # becomes my_function("a b c")
214 214
215 215 Note that the ',' MUST be the first character on the line! This
216 216 won't work:
217 217 >>> x = ,my_function /home/me # syntax error
218 218 """
219 219
220 220 interactive_usage_min = """\
221 221 An enhanced console for Python.
222 222 Some of its features are:
223 223 - Readline support if the readline library is present.
224 224 - Tab completion in the local namespace.
225 225 - Logging of input, see command-line options.
226 226 - System shell escape via ! , eg !ls.
227 227 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
228 228 - Keeps track of locally defined variables via %who, %whos.
229 229 - Show object information with a ? eg ?x or x? (use ?? for more info).
230 230 """
231 231
232 232 quick_reference = r"""
233 233 IPython -- An enhanced Interactive Python - Quick Reference Card
234 234 ================================================================
235 235
236 236 obj?, obj?? : Get help, or more help for object (also works as
237 237 ?obj, ??obj).
238 238 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
239 239 %magic : Information about IPython's 'magic' % functions.
240 240
241 241 Magic functions are prefixed by %, and typically take their arguments without
242 242 parentheses, quotes or even commas for convenience.
243 243
244 244 Example magic function calls:
245 245
246 246 %alias d ls -F : 'd' is now an alias for 'ls -F'
247 247 alias d ls -F : Works if 'alias' not a python name
248 248 alist = %alias : Get list of aliases to 'alist'
249 249 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
250 250 %cd?? : See help AND source for magic %cd
251 251
252 252 System commands:
253 253
254 254 !cp a.txt b/ : System command escape, calls os.system()
255 255 cp a.txt b/ : after %rehashx, most system commands work without !
256 256 cp ${f}.txt $bar : Variable expansion in magics and system commands
257 257 files = !ls /usr : Capture sytem command output
258 258 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
259 259
260 260 History:
261 261
262 262 _i, _ii, _iii : Previous, next previous, next next previous input
263 263 _i4, _ih[2:5] : Input history line 4, lines 2-4
264 264 exec _i81 : Execute input history line #81 again
265 265 %rep 81 : Edit input history line #81
266 266 _, __, ___ : previous, next previous, next next previous output
267 267 _dh : Directory history
268 268 _oh : Output history
269 269 %hist : Command history. '%hist -g foo' search history for 'foo'
270 270
271 271 Autocall:
272 272
273 273 f 1,2 : f(1,2)
274 274 /f 1,2 : f(1,2) (forced autoparen)
275 275 ,f 1 2 : f("1","2")
276 276 ;f 1 2 : f("1 2")
277 277
278 278 Remember: TAB completion works in many contexts, not just file names
279 279 or python names.
280 280
281 281 The following magic functions are currently available:
282 282
283 283 """
284 284
285 285 gui_reference = """\
286 286 ===============================
287 287 The graphical IPython console
288 288 ===============================
289 289
290 290 This console is designed to emulate the look, feel and workflow of a terminal
291 291 environment, while adding a number of enhancements that are simply not possible
292 292 in a real terminal, such as inline syntax highlighting, true multiline editing,
293 293 inline graphics and much more.
294 294
295 295 This quick reference document contains the basic information you'll need to
296 296 know to make the most efficient use of it. For the various command line
297 297 options available at startup, type ``--help`` at the command line.
298 298
299 299
300 300 Multiline editing
301 301 =================
302 302
303 303 The graphical console is capable of true multiline editing, but it also tries
304 304 to behave intuitively like a terminal when possible. If you are used to
305 305 IPyhton's old terminal behavior, you should find the transition painless, and
306 306 once you learn a few basic keybindings it will be a much more efficient
307 307 environment.
308 308
309 309 For single expressions or indented blocks, the console behaves almost like the
310 310 terminal IPython: single expressions are immediately evaluated, and indented
311 311 blocks are evaluated once a single blank line is entered::
312 312
313 313 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
314 314 Hello IPython!
315 315
316 316 In [2]: for i in range(10):
317 317 ...: print i,
318 318 ...:
319 319 0 1 2 3 4 5 6 7 8 9
320 320
321 321 If you want to enter more than one expression in a single input block
322 322 (something not possible in the terminal), you can use ``Control-Enter`` at the
323 323 end of your first line instead of ``Enter``. At that point the console goes
324 324 into 'cell mode' and even if your inputs are not indented, it will continue
325 325 accepting arbitrarily many lines until either you enter an extra blank line or
326 326 you hit ``Shift-Enter`` (the key binding that forces execution). When a
327 327 multiline cell is entered, IPython analyzes it and executes its code producing
328 328 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
329 329 cell is executed as if it was a script. An example should clarify this::
330 330
331 331 In [3]: x=1 # Hit C-Enter here
332 332 ...: y=2 # from now on, regular Enter is sufficient
333 333 ...: z=3
334 334 ...: x**2 # This does *not* produce an Out[] value
335 335 ...: x+y+z # Only the last expression does
336 336 ...:
337 337 Out[3]: 6
338 338
339 339 The behavior where an extra blank line forces execution is only active if you
340 340 are actually typing at the keyboard each line, and is meant to make it mimic
341 341 the IPython terminal behavior. If you paste a long chunk of input (for example
342 342 a long script copied form an editor or web browser), it can contain arbitrarily
343 343 many intermediate blank lines and they won't cause any problems. As always,
344 344 you can then make it execute by appending a blank line *at the end* or hitting
345 345 ``Shift-Enter`` anywhere within the cell.
346 346
347 347 With the up arrow key, you can retrieve previous blocks of input that contain
348 348 multiple lines. You can move inside of a multiline cell like you would in any
349 349 text editor. When you want it executed, the simplest thing to do is to hit the
350 350 force execution key, ``Shift-Enter`` (though you can also navigate to the end
351 351 and append a blank line by using ``Enter`` twice).
352 352
353 353 If you've edited a multiline cell and accidentally navigate out of it with the
354 354 up or down arrow keys, IPython will clear the cell and replace it with the
355 355 contents of the one above or below that you navigated to. If this was an
356 356 accident and you want to retrieve the cell you were editing, use the Undo
357 357 keybinding, ``Control-z``.
358 358
359 359
360 360 Key bindings
361 361 ============
362 362
363 363 The IPython console supports most of the basic Emacs line-oriented keybindings,
364 364 in addition to some of its own.
365 365
366 366 The keybinding prefixes mean:
367 367
368 368 - ``C``: Control
369 369 - ``S``: Shift
370 370 - ``M``: Meta (typically the Alt key)
371 371
372 372 The keybindings themselves are:
373 373
374 374 - ``Enter``: insert new line (may cause execution, see above).
375 375 - ``C-Enter``: force new line, *never* causes execution.
376 376 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
377 377 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
378 378 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
379 379 - ``C-v``: paste text from clipboard.
380 380 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
381 381 - ``C-S-z``: redo.
382 382 - ``C-o``: move to 'other' area, between pager and terminal.
383 383 - ``C-l``: clear terminal.
384 384 - ``C-a``: go to beginning of line.
385 385 - ``C-e``: go to end of line.
386 386 - ``C-k``: kill from cursor to the end of the line.
387 387 - ``C-y``: yank (paste)
388 388 - ``C-p``: previous line (like up arrow)
389 389 - ``C-n``: next line (like down arrow)
390 390 - ``C-f``: forward (like right arrow)
391 391 - ``C-b``: back (like left arrow)
392 392 - ``C-d``: delete next character.
393 393 - ``M-<``: move to the beginning of the input region.
394 394 - ``M->``: move to the end of the input region.
395 395 - ``M-d``: delete next word.
396 396 - ``M-Backspace``: delete previous word.
397 397 - ``C-.``: force a kernel restart (a confirmation dialog appears).
398 398 - ``C-+``: increase font size.
399 399 - ``C--``: decrease font size.
400 400
401 401 The IPython pager
402 402 =================
403 403
404 404 IPython will show long blocks of text from many sources using a builtin pager.
405 405 You can control where this pager appears with the ``--paging`` command-line
406 406 flag:
407 407
408 408 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
409 409 must quit the pager to get back to the terminal (similar to how a pager such
410 410 as ``less`` or ``more`` works).
411 411
412 412 - ``vsplit``: the console is made double-tall, and the pager appears on the
413 413 bottom area when needed. You can view its contents while using the terminal.
414 414
415 415 - ``hsplit``: the console is made double-wide, and the pager appears on the
416 416 right area when needed. You can view its contents while using the terminal.
417 417
418 418 - ``none``: the console never pages output.
419 419
420 420 If you use the vertical or horizontal paging modes, you can navigate between
421 421 terminal and pager as follows:
422 422
423 423 - Tab key: goes from pager to terminal (but not the other way around).
424 424 - Control-o: goes from one to another always.
425 425 - Mouse: click on either.
426 426
427 427 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
428 428 focus on the pager area).
429 429
430 430 Running subprocesses
431 431 ====================
432 432
433 433 The graphical IPython console uses the ``pexpect`` module to run subprocesses
434 434 when you type ``!command``. This has a number of advantages (true asynchronous
435 435 output from subprocesses as well as very robust termination of rogue
436 436 subprocesses with ``Control-C``), as well as some limitations. The main
437 437 limitation is that you can *not* interact back with the subprocess, so anything
438 438 that invokes a pager or expects you to type input into it will block and hang
439 439 (you can kill it with ``Control-C``).
440 440
441 441 We have provided as magics ``%less`` to page files (aliased to ``%more``),
442 442 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
443 443 most common commands you'd want to call in your subshell and that would cause
444 444 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
445 445
446 446 Display
447 447 =======
448 448
449 449 The IPython console can now display objects in a variety of formats, including
450 450 HTML, PNG and SVG. This is accomplished using the display functions in
451 451 ``IPython.core.display``::
452 452
453 453 In [4]: from IPython.core.display import display, display_html
454 454
455 455 In [5]: from IPython.core.display import display_png, display_svg
456 456
457 457 Python objects can simply be passed to these functions and the appropriate
458 458 representations will be displayed in the console as long as the objects know
459 459 how to compute those representations. The easiest way of teaching objects how
460 460 to format themselves in various representations is to define special methods
461 such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters
461 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
462 462 can also be given custom formatter functions for various types::
463 463
464 464 In [6]: ip = get_ipython()
465 465
466 466 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
467 467
468 468 In [8]: html_formatter.for_type(Foo, foo_to_html)
469 469
470 470 For further details, see ``IPython.core.formatters``.
471 471
472 472 Inline matplotlib graphics
473 473 ==========================
474 474
475 475 The IPython console is capable of displaying matplotlib figures inline, in SVG
476 476 format. If started with the ``--pylab inline`` flag, then all figures are
477 477 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
478 478 backend>``, then a GUI backend will be used, but IPython's ``display()`` and
479 479 ``getfigs()`` functions can be used to view plots inline::
480 480
481 481 In [9]: display(*getfigs()) # display all figures inline
482 482
483 483 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
484 484 """
485 485
486 486
487 487 quick_guide = """\
488 488 ? -> Introduction and overview of IPython's features.
489 489 %quickref -> Quick reference.
490 490 help -> Python's own help system.
491 491 object? -> Details about 'object', use 'object??' for extra details.
492 492 """
493 493
494 494 gui_note = """\
495 495 %guiref -> A brief reference about the graphical user interface.
496 496 """
497 497
498 498 default_banner_parts = [
499 499 'Python %s\n' % (sys.version.split('\n')[0],),
500 500 'Type "copyright", "credits" or "license" for more information.\n\n',
501 501 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
502 502 quick_guide
503 503 ]
504 504
505 505 default_gui_banner_parts = default_banner_parts + [gui_note]
506 506
507 507 default_banner = ''.join(default_banner_parts)
508 508
509 509 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,70 +1,70 b''
1 1 """A print function that pretty prints sympy Basic objects.
2 2
3 3 Authors:
4 4 * Brian Granger
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from IPython.lib.latextools import latex_to_png
18 18 from IPython.testing import decorators as dec
19 19 # use @dec.skipif_not_sympy to skip tests requiring sympy
20 20
21 21 try:
22 22 from sympy import pretty, latex
23 23 except ImportError:
24 24 pass
25 25
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Definitions of magic functions for use with IPython
29 29 #-----------------------------------------------------------------------------
30 30
31 31 def print_basic_unicode(o, p, cycle):
32 32 """A function to pretty print sympy Basic objects."""
33 33 if cycle:
34 34 return p.text('Basic(...)')
35 35 out = pretty(o, use_unicode=True)
36 36 if '\n' in out:
37 37 p.text(u'\n')
38 38 p.text(out)
39 39
40 40
41 41 def print_png(o):
42 """A funciton to display sympy expression using LaTex -> PNG."""
42 """A function to display sympy expression using LaTex -> PNG."""
43 43 s = latex(o, mode='inline')
44 44 # mathtext does not understand certain latex flags, so we try to replace
45 45 # them with suitable subs.
46 46 s = s.replace('\\operatorname','')
47 47 s = s.replace('\\overline', '\\bar')
48 48 png = latex_to_png(s, encode=True)
49 49 return png
50 50
51 51 _loaded = False
52 52
53 53 def load_ipython_extension(ip):
54 54 """Load the extension in IPython."""
55 55 global _loaded
56 56 if not _loaded:
57 57 plaintext_formatter = ip.display_formatter.formatters['text/plain']
58 58 plaintext_formatter.for_type_by_name(
59 59 'sympy.core.basic', 'Basic', print_basic_unicode
60 60 )
61 61 plaintext_formatter.for_type_by_name(
62 62 'sympy.matrices.matrices', 'Matrix', print_basic_unicode
63 63 )
64 64
65 65 png_formatter = ip.display_formatter.formatters['image/png']
66 66 png_formatter.for_type_by_name(
67 67 'sympy.core.basic', 'Basic', print_png
68 68 )
69 69 _loaded = True
70 70
@@ -1,299 +1,300 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Pylab (matplotlib) support utilities.
3 3
4 4 Authors
5 5 -------
6 6
7 7 * Fernando Perez.
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 from cStringIO import StringIO
23 23
24 24 from IPython.utils.decorators import flag_calls
25 25
26 26 # If user specifies a GUI, that dictates the backend, otherwise we read the
27 27 # user's mpl default from the mpl rc structure
28 28 backends = {'tk': 'TkAgg',
29 29 'gtk': 'GTKAgg',
30 30 'wx': 'WXAgg',
31 31 'qt': 'Qt4Agg', # qt3 not supported
32 32 'qt4': 'Qt4Agg',
33 33 'osx': 'MacOSX',
34 34 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Matplotlib utilities
38 38 #-----------------------------------------------------------------------------
39 39
40 40
41 41 def getfigs(*fig_nums):
42 42 """Get a list of matplotlib figures by figure numbers.
43 43
44 44 If no arguments are given, all available figures are returned. If the
45 45 argument list contains references to invalid figures, a warning is printed
46 46 but the function continues pasting further figures.
47 47
48 48 Parameters
49 49 ----------
50 50 figs : tuple
51 51 A tuple of ints giving the figure numbers of the figures to return.
52 52 """
53 53 from matplotlib._pylab_helpers import Gcf
54 54 if not fig_nums:
55 55 fig_managers = Gcf.get_all_fig_managers()
56 56 return [fm.canvas.figure for fm in fig_managers]
57 57 else:
58 58 figs = []
59 59 for num in fig_nums:
60 60 f = Gcf.figs.get(num)
61 61 if f is None:
62 62 print('Warning: figure %s not available.' % num)
63 figs.append(f.canvas.figure)
63 else:
64 figs.append(f.canvas.figure)
64 65 return figs
65 66
66 67
67 68 def figsize(sizex, sizey):
68 69 """Set the default figure size to be [sizex, sizey].
69 70
70 71 This is just an easy to remember, convenience wrapper that sets::
71 72
72 73 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
73 74 """
74 75 import matplotlib
75 76 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
76 77
77 78
78 79 def figure_to_svg(fig):
79 80 """Convert a figure to svg for inline display."""
80 81 # When there's an empty figure, we shouldn't return anything, otherwise we
81 82 # get big blank areas in the qt console.
82 83 if not fig.axes:
83 84 return
84 85
85 86 fc = fig.get_facecolor()
86 87 ec = fig.get_edgecolor()
87 88 fig.set_facecolor('white')
88 89 fig.set_edgecolor('white')
89 90 try:
90 91 string_io = StringIO()
91 92 fig.canvas.print_figure(string_io, format='svg')
92 93 svg = string_io.getvalue()
93 94 finally:
94 95 fig.set_facecolor(fc)
95 96 fig.set_edgecolor(ec)
96 97 return svg
97 98
98 99
99 100 # We need a little factory function here to create the closure where
100 101 # safe_execfile can live.
101 102 def mpl_runner(safe_execfile):
102 103 """Factory to return a matplotlib-enabled runner for %run.
103 104
104 105 Parameters
105 106 ----------
106 107 safe_execfile : function
107 108 This must be a function with the same interface as the
108 109 :meth:`safe_execfile` method of IPython.
109 110
110 111 Returns
111 112 -------
112 113 A function suitable for use as the ``runner`` argument of the %run magic
113 114 function.
114 115 """
115 116
116 117 def mpl_execfile(fname,*where,**kw):
117 118 """matplotlib-aware wrapper around safe_execfile.
118 119
119 120 Its interface is identical to that of the :func:`execfile` builtin.
120 121
121 122 This is ultimately a call to execfile(), but wrapped in safeties to
122 123 properly handle interactive rendering."""
123 124
124 125 import matplotlib
125 126 import matplotlib.pylab as pylab
126 127
127 128 #print '*** Matplotlib runner ***' # dbg
128 129 # turn off rendering until end of script
129 130 is_interactive = matplotlib.rcParams['interactive']
130 131 matplotlib.interactive(False)
131 132 safe_execfile(fname,*where,**kw)
132 133 matplotlib.interactive(is_interactive)
133 134 # make rendering call now, if the user tried to do it
134 135 if pylab.draw_if_interactive.called:
135 136 pylab.draw()
136 137 pylab.draw_if_interactive.called = False
137 138
138 139 return mpl_execfile
139 140
140 141
141 142 #-----------------------------------------------------------------------------
142 143 # Code for initializing matplotlib and importing pylab
143 144 #-----------------------------------------------------------------------------
144 145
145 146
146 147 def find_gui_and_backend(gui=None):
147 148 """Given a gui string return the gui and mpl backend.
148 149
149 150 Parameters
150 151 ----------
151 152 gui : str
152 153 Can be one of ('tk','gtk','wx','qt','qt4','inline').
153 154
154 155 Returns
155 156 -------
156 157 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
157 158 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
158 159 """
159 160
160 161 import matplotlib
161 162
162 163 if gui:
163 164 # select backend based on requested gui
164 165 backend = backends[gui]
165 166 else:
166 167 backend = matplotlib.rcParams['backend']
167 168 # In this case, we need to find what the appropriate gui selection call
168 169 # should be for IPython, so we can activate inputhook accordingly
169 170 g2b = backends # maps gui names to mpl backend names
170 171 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
171 172 gui = b2g.get(backend, None)
172 173 return gui, backend
173 174
174 175
175 176 def activate_matplotlib(backend):
176 177 """Activate the given backend and set interactive to True."""
177 178
178 179 import matplotlib
179 180 if backend.startswith('module://'):
180 181 # Work around bug in matplotlib: matplotlib.use converts the
181 182 # backend_id to lowercase even if a module name is specified!
182 183 matplotlib.rcParams['backend'] = backend
183 184 else:
184 185 matplotlib.use(backend)
185 186 matplotlib.interactive(True)
186 187
187 188 # This must be imported last in the matplotlib series, after
188 189 # backend/interactivity choices have been made
189 190 import matplotlib.pylab as pylab
190 191
191 192 # XXX For now leave this commented out, but depending on discussions with
192 193 # mpl-dev, we may be able to allow interactive switching...
193 194 #import matplotlib.pyplot
194 195 #matplotlib.pyplot.switch_backend(backend)
195 196
196 197 pylab.show._needmain = False
197 198 # We need to detect at runtime whether show() is called by the user.
198 199 # For this, we wrap it into a decorator which adds a 'called' flag.
199 200 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
200 201
201 202
202 203 def import_pylab(user_ns, backend, import_all=True, shell=None):
203 204 """Import the standard pylab symbols into user_ns."""
204 205
205 206 # Import numpy as np/pyplot as plt are conventions we're trying to
206 207 # somewhat standardize on. Making them available to users by default
207 208 # will greatly help this.
208 209 s = ("import numpy\n"
209 210 "import matplotlib\n"
210 211 "from matplotlib import pylab, mlab, pyplot\n"
211 212 "np = numpy\n"
212 213 "plt = pyplot\n"
213 214 )
214 215 exec s in user_ns
215 216
216 217 if shell is not None:
217 218 exec s in shell.user_ns_hidden
218 219 # If using our svg payload backend, register the post-execution
219 220 # function that will pick up the results for display. This can only be
220 221 # done with access to the real shell object.
221 222 if backend == backends['inline']:
222 223 from IPython.zmq.pylab.backend_inline import flush_svg
223 224 from matplotlib import pyplot
224 225 shell.register_post_execute(flush_svg)
225 226 # The typical default figure size is too large for inline use,
226 227 # so we shrink the figure size to 6x4, and tweak fonts to
227 228 # make that fit. This is configurable via Global.pylab_inline_rc,
228 229 # or rather it will be once the zmq kernel is hooked up to
229 230 # the config system.
230 231
231 232 default_rc = {
232 233 'figure.figsize': (6.0,4.0),
233 234 # 12pt labels get cutoff on 6x4 logplots, so use 10pt.
234 235 'font.size': 10,
235 236 # 10pt still needs a little more room on the xlabel:
236 237 'figure.subplot.bottom' : .125
237 238 }
238 239 rc = getattr(shell.config.Global, 'pylab_inline_rc', default_rc)
239 240 pyplot.rcParams.update(rc)
240 241 shell.config.Global.pylab_inline_rc = rc
241 242
242 243 # Add 'figsize' to pyplot and to the user's namespace
243 244 user_ns['figsize'] = pyplot.figsize = figsize
244 245 shell.user_ns_hidden['figsize'] = figsize
245 246
246 247 # The old pastefig function has been replaced by display
247 248 # Always add this svg formatter so display works.
248 249 from IPython.core.display import display, display_svg
249 250 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
250 251 svg_formatter.for_type_by_name(
251 252 'matplotlib.figure','Figure',figure_to_svg
252 253 )
253 254 # Add display and display_png to the user's namespace
254 255 user_ns['display'] = display
255 256 shell.user_ns_hidden['display'] = display
256 257 user_ns['display_svg'] = display_svg
257 258 shell.user_ns_hidden['display_svg'] = display_svg
258 259 user_ns['getfigs'] = getfigs
259 260 shell.user_ns_hidden['getfigs'] = getfigs
260 261
261 262 if import_all:
262 263 s = ("from matplotlib.pylab import *\n"
263 264 "from numpy import *\n")
264 265 exec s in user_ns
265 266 if shell is not None:
266 267 exec s in shell.user_ns_hidden
267 268
268 269
269 270 def pylab_activate(user_ns, gui=None, import_all=True):
270 271 """Activate pylab mode in the user's namespace.
271 272
272 273 Loads and initializes numpy, matplotlib and friends for interactive use.
273 274
274 275 Parameters
275 276 ----------
276 277 user_ns : dict
277 278 Namespace where the imports will occur.
278 279
279 280 gui : optional, string
280 281 A valid gui name following the conventions of the %gui magic.
281 282
282 283 import_all : optional, boolean
283 284 If true, an 'import *' is done from numpy and pylab.
284 285
285 286 Returns
286 287 -------
287 288 The actual gui used (if not given as input, it was obtained from matplotlib
288 289 itself, and will be needed next to configure IPython's gui integration.
289 290 """
290 291 gui, backend = find_gui_and_backend(gui)
291 292 activate_matplotlib(backend)
292 293 import_pylab(user_ns, backend)
293 294
294 295 print """
295 296 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
296 297 For more information, type 'help(pylab)'.""" % backend
297 298
298 299 return gui
299 300
General Comments 0
You need to be logged in to leave comments. Login now