##// END OF EJS Templates
add a little detail to custom repr method docs (#13945)...
Matthias Bussonnier -
r28126:29190f63 merge
parent child Browse files
Show More
@@ -1,172 +1,184 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
143
132
144
133 Metadata
145 Metadata
134 ^^^^^^^^
146 ^^^^^^^^
135
147
136 We often want to provide frontends with guidance on how to display the data. To
148 We often want to provide frontends with guidance on how to display the data. To
137 support this, ``_repr_*_()`` methods (except ``_repr_pretty_``?) can also return a ``(data, metadata)``
149 support this, ``_repr_*_()`` methods (except ``_repr_pretty_``?) can also return a ``(data, metadata)``
138 tuple where ``metadata`` is a dictionary containing arbitrary key-value pairs for
150 tuple where ``metadata`` is a dictionary containing arbitrary key-value pairs for
139 the frontend to interpret. An example use case is ``_repr_jpeg_()``, which can
151 the frontend to interpret. An example use case is ``_repr_jpeg_()``, which can
140 be set to return a jpeg image and a ``{'height': 400, 'width': 600}`` dictionary
152 be set to return a jpeg image and a ``{'height': 400, 'width': 600}`` dictionary
141 to inform the frontend how to size the image.
153 to inform the frontend how to size the image.
142
154
143
155
144
156
145 Formatters for third-party types
157 Formatters for third-party types
146 --------------------------------
158 --------------------------------
147
159
148 The user can also register formatters for types without modifying the class::
160 The user can also register formatters for types without modifying the class::
149
161
150 from bar.baz import Foo
162 from bar.baz import Foo
151
163
152 def foo_html(obj):
164 def foo_html(obj):
153 return '<marquee>Foo object %s</marquee>' % obj.name
165 return '<marquee>Foo object %s</marquee>' % obj.name
154
166
155 html_formatter = get_ipython().display_formatter.formatters['text/html']
167 html_formatter = get_ipython().display_formatter.formatters['text/html']
156 html_formatter.for_type(Foo, foo_html)
168 html_formatter.for_type(Foo, foo_html)
157
169
158 # Or register a type without importing it - this does the same as above:
170 # Or register a type without importing it - this does the same as above:
159 html_formatter.for_type_by_name('bar.baz', 'Foo', foo_html)
171 html_formatter.for_type_by_name('bar.baz', 'Foo', foo_html)
160
172
161 Custom exception tracebacks
173 Custom exception tracebacks
162 ===========================
174 ===========================
163
175
164 Rarely, you might want to display a custom traceback when reporting an
176 Rarely, you might want to display a custom traceback when reporting an
165 exception. To do this, define the custom traceback using
177 exception. To do this, define the custom traceback using
166 `_render_traceback_(self)` method which returns a list of strings, one string
178 `_render_traceback_(self)` method which returns a list of strings, one string
167 for each line of the traceback. For example, the `ipyparallel
179 for each line of the traceback. For example, the `ipyparallel
168 <https://ipyparallel.readthedocs.io/>`__ a parallel computing framework for
180 <https://ipyparallel.readthedocs.io/>`__ a parallel computing framework for
169 IPython, does this to display errors from multiple engines.
181 IPython, does this to display errors from multiple engines.
170
182
171 Please be conservative in using this feature; by replacing the default traceback
183 Please be conservative in using this feature; by replacing the default traceback
172 you may hide important information from the user.
184 you may hide important information from the user.
General Comments 0
You need to be logged in to leave comments. Login now