##// END OF EJS Templates
add a little detail to custom repr method docs...
Min RK -
Show More
@@ -1,173 +1,185 b''
1 .. _integrating:
1 .. _integrating:
2
2
3 =====================================
3 =====================================
4 Integrating your objects with IPython
4 Integrating your objects with IPython
5 =====================================
5 =====================================
6
6
7 Tab completion
7 Tab completion
8 ==============
8 ==============
9
9
10 To change the attributes displayed by tab-completing your object, define a
10 To change the attributes displayed by tab-completing your object, define a
11 ``__dir__(self)`` method for it. For more details, see the documentation of the
11 ``__dir__(self)`` method for it. For more details, see the documentation of the
12 built-in `dir() function <http://docs.python.org/library/functions.html#dir>`_.
12 built-in `dir() function <http://docs.python.org/library/functions.html#dir>`_.
13
13
14 You can also customise key completions for your objects, e.g. pressing tab after
14 You can also customise key completions for your objects, e.g. pressing tab after
15 ``obj["a``. To do so, define a method ``_ipython_key_completions_()``, which
15 ``obj["a``. To do so, define a method ``_ipython_key_completions_()``, which
16 returns a list of objects which are possible keys in a subscript expression
16 returns a list of objects which are possible keys in a subscript expression
17 ``obj[key]``.
17 ``obj[key]``.
18
18
19 .. versionadded:: 5.0
19 .. versionadded:: 5.0
20 Custom key completions
20 Custom key completions
21
21
22 .. _integrating_rich_display:
22 .. _integrating_rich_display:
23
23
24 Rich display
24 Rich display
25 ============
25 ============
26
26
27 Custom methods
27 Custom methods
28 ----------------------
28 ----------------------
29
29 IPython can display richer representations of objects.
30 IPython can display richer representations of objects.
30 To do this, you can define ``_ipython_display_()``, or any of a number of
31 To do this, you can define ``_ipython_display_()``, or any of a number of
31 ``_repr_*_()`` methods.
32 ``_repr_*_()`` methods.
32 Note that these are surrounded by single, not double underscores.
33 Note that these are surrounded by single, not double underscores.
33
34
35
34 .. list-table:: Supported ``_repr_*_`` methods
36 .. list-table:: Supported ``_repr_*_`` methods
35 :widths: 20 15 15 15
37 :widths: 20 15 15 15
36 :header-rows: 1
38 :header-rows: 1
37
39
38 * - Format
40 * - Format
39 - REPL
41 - REPL
40 - Notebook
42 - Notebook
41 - Qt Console
43 - Qt Console
42 * - ``_repr_pretty_``
44 * - ``_repr_pretty_``
43 - yes
45 - yes
44 - yes
46 - yes
45 - yes
47 - yes
46 * - ``_repr_svg_``
48 * - ``_repr_svg_``
47 - no
49 - no
48 - yes
50 - yes
49 - yes
51 - yes
50 * - ``_repr_png_``
52 * - ``_repr_png_``
51 - no
53 - no
52 - yes
54 - yes
53 - yes
55 - yes
54 * - ``_repr_jpeg_``
56 * - ``_repr_jpeg_``
55 - no
57 - no
56 - yes
58 - yes
57 - yes
59 - yes
58 * - ``_repr_html_``
60 * - ``_repr_html_``
59 - no
61 - no
60 - yes
62 - yes
61 - no
63 - no
62 * - ``_repr_javascript_``
64 * - ``_repr_javascript_``
63 - no
65 - no
64 - yes
66 - yes
65 - no
67 - no
66 * - ``_repr_markdown_``
68 * - ``_repr_markdown_``
67 - no
69 - no
68 - yes
70 - yes
69 - no
71 - no
70 * - ``_repr_latex_``
72 * - ``_repr_latex_``
71 - no
73 - no
72 - yes
74 - yes
73 - no
75 - no
74 * - ``_repr_mimebundle_``
76 * - ``_repr_mimebundle_``
75 - no
77 - no
76 - ?
78 - ?
77 - ?
79 - ?
78
80
79 If the methods don't exist, or return ``None``, the standard ``repr()`` is used.
81 If the methods don't exist, the standard ``repr()`` is used.
82 If a method exists and returns ``None``, it is treated the same as if it does not exist.
83 In general, *all* available formatters will be called when an object is displayed,
84 and it is up to the UI to select which to display.
85 A given formatter should not generally change its output based on what other formats are available -
86 that should be handled at a different level, such as the :class:`~.DisplayFormatter`, or configuration.
87
88 ``_repr_*_`` methods should *return* data of the expected format and have no side effects.
89 For example, ``_repr_html_`` should return HTML as a `str` and ``_repr_png_`` should return PNG data as `bytes`.
90
91 If you wish to take control of display via your own side effects, use ``_ipython_display_()``.
80
92
81 For example::
93 For example::
82
94
83 class Shout(object):
95 class Shout(object):
84 def __init__(self, text):
96 def __init__(self, text):
85 self.text = text
97 self.text = text
86
98
87 def _repr_html_(self):
99 def _repr_html_(self):
88 return "<h1>" + self.text + "</h1>"
100 return "<h1>" + self.text + "</h1>"
89
101
90
102
91 Special methods
103 Special methods
92 ^^^^^^^^^^^^^^^
104 ^^^^^^^^^^^^^^^
93
105
94 Pretty printing
106 Pretty printing
95 """""""""""""""
107 """""""""""""""
96
108
97 To customize how your object is pretty-printed, add a ``_repr_pretty_`` method
109 To customize how your object is pretty-printed, add a ``_repr_pretty_`` method
98 to the class.
110 to the class.
99 The method should accept a pretty printer, and a boolean that indicates whether
111 The method should accept a pretty printer, and a boolean that indicates whether
100 the printer detected a cycle.
112 the printer detected a cycle.
101 The method should act on the printer to produce your customized pretty output.
113 The method should act on the printer to produce your customized pretty output.
102 Here is an example::
114 Here is an example::
103
115
104 class MyObject(object):
116 class MyObject(object):
105
117
106 def _repr_pretty_(self, p, cycle):
118 def _repr_pretty_(self, p, cycle):
107 if cycle:
119 if cycle:
108 p.text('MyObject(...)')
120 p.text('MyObject(...)')
109 else:
121 else:
110 p.text('MyObject[...]')
122 p.text('MyObject[...]')
111
123
112 For details on how to use the pretty printer, see :py:mod:`IPython.lib.pretty`.
124 For details on how to use the pretty printer, see :py:mod:`IPython.lib.pretty`.
113
125
114 More powerful methods
126 More powerful methods
115 """""""""""""""""""""
127 """""""""""""""""""""
116
128
117 .. class:: MyObject
129 .. class:: MyObject
118
130
119 .. method:: _repr_mimebundle_(include=None, exclude=None)
131 .. method:: _repr_mimebundle_(include=None, exclude=None)
120
132
121 Should return a dictionary of multiple formats, keyed by mimetype, or a tuple
133 Should return a dictionary of multiple formats, keyed by mimetype, or a tuple
122 of two dictionaries: *data, metadata* (see :ref:`Metadata`).
134 of two dictionaries: *data, metadata* (see :ref:`Metadata`).
123 If this returns something, other ``_repr_*_`` methods are ignored.
135 If this returns something, other ``_repr_*_`` methods are ignored.
124 The method should take keyword arguments ``include`` and ``exclude``, though
136 The method should take keyword arguments ``include`` and ``exclude``, though
125 it is not required to respect them.
137 it is not required to respect them.
126
138
127 .. method:: _ipython_display_()
139 .. method:: _ipython_display_()
128
140
129 Displays the object as a side effect; the return value is ignored. If this
141 Displays the object as a side effect; the return value is ignored. If this
130 is defined, all other display methods are ignored.
142 is defined, all other display methods are ignored.
131 This method is ignored in the REPL.
143 This method is ignored in the REPL.
132
144
133
145
134 Metadata
146 Metadata
135 ^^^^^^^^
147 ^^^^^^^^
136
148
137 We often want to provide frontends with guidance on how to display the data. To
149 We often want to provide frontends with guidance on how to display the data. To
138 support this, ``_repr_*_()`` methods (except ``_repr_pretty_``?) can also return a ``(data, metadata)``
150 support this, ``_repr_*_()`` methods (except ``_repr_pretty_``?) can also return a ``(data, metadata)``
139 tuple where ``metadata`` is a dictionary containing arbitrary key-value pairs for
151 tuple where ``metadata`` is a dictionary containing arbitrary key-value pairs for
140 the frontend to interpret. An example use case is ``_repr_jpeg_()``, which can
152 the frontend to interpret. An example use case is ``_repr_jpeg_()``, which can
141 be set to return a jpeg image and a ``{'height': 400, 'width': 600}`` dictionary
153 be set to return a jpeg image and a ``{'height': 400, 'width': 600}`` dictionary
142 to inform the frontend how to size the image.
154 to inform the frontend how to size the image.
143
155
144
156
145
157
146 Formatters for third-party types
158 Formatters for third-party types
147 --------------------------------
159 --------------------------------
148
160
149 The user can also register formatters for types without modifying the class::
161 The user can also register formatters for types without modifying the class::
150
162
151 from bar.baz import Foo
163 from bar.baz import Foo
152
164
153 def foo_html(obj):
165 def foo_html(obj):
154 return '<marquee>Foo object %s</marquee>' % obj.name
166 return '<marquee>Foo object %s</marquee>' % obj.name
155
167
156 html_formatter = get_ipython().display_formatter.formatters['text/html']
168 html_formatter = get_ipython().display_formatter.formatters['text/html']
157 html_formatter.for_type(Foo, foo_html)
169 html_formatter.for_type(Foo, foo_html)
158
170
159 # Or register a type without importing it - this does the same as above:
171 # Or register a type without importing it - this does the same as above:
160 html_formatter.for_type_by_name('bar.baz', 'Foo', foo_html)
172 html_formatter.for_type_by_name('bar.baz', 'Foo', foo_html)
161
173
162 Custom exception tracebacks
174 Custom exception tracebacks
163 ===========================
175 ===========================
164
176
165 Rarely, you might want to display a custom traceback when reporting an
177 Rarely, you might want to display a custom traceback when reporting an
166 exception. To do this, define the custom traceback using
178 exception. To do this, define the custom traceback using
167 `_render_traceback_(self)` method which returns a list of strings, one string
179 `_render_traceback_(self)` method which returns a list of strings, one string
168 for each line of the traceback. For example, the `ipyparallel
180 for each line of the traceback. For example, the `ipyparallel
169 <https://ipyparallel.readthedocs.io/>`__ a parallel computing framework for
181 <https://ipyparallel.readthedocs.io/>`__ a parallel computing framework for
170 IPython, does this to display errors from multiple engines.
182 IPython, does this to display errors from multiple engines.
171
183
172 Please be conservative in using this feature; by replacing the default traceback
184 Please be conservative in using this feature; by replacing the default traceback
173 you may hide important information from the user.
185 you may hide important information from the user.
General Comments 0
You need to be logged in to leave comments. Login now