Show More
@@ -1,212 +1,212 b'' | |||||
1 | .. _defining_magics: |
|
1 | .. _defining_magics: | |
2 |
|
2 | |||
3 | Defining custom magics |
|
3 | Defining custom magics | |
4 | ====================== |
|
4 | ====================== | |
5 |
|
5 | |||
6 | There are two main ways to define your own magic functions: from standalone |
|
6 | There are two main ways to define your own magic functions: from standalone | |
7 | functions and by inheriting from a base class provided by IPython: |
|
7 | functions and by inheriting from a base class provided by IPython: | |
8 | :class:`IPython.core.magic.Magics`. Below we show code you can place in a file |
|
8 | :class:`IPython.core.magic.Magics`. Below we show code you can place in a file | |
9 | that you load from your configuration, such as any file in the ``startup`` |
|
9 | that you load from your configuration, such as any file in the ``startup`` | |
10 | subdirectory of your default IPython profile. |
|
10 | subdirectory of your default IPython profile. | |
11 |
|
11 | |||
12 | First, let us see the simplest case. The following shows how to create a line |
|
12 | First, let us see the simplest case. The following shows how to create a line | |
13 | magic, a cell one and one that works in both modes, using just plain functions: |
|
13 | magic, a cell one and one that works in both modes, using just plain functions: | |
14 |
|
14 | |||
15 | .. sourcecode:: python |
|
15 | .. sourcecode:: python | |
16 |
|
16 | |||
17 | from IPython.core.magic import (register_line_magic, register_cell_magic, |
|
17 | from IPython.core.magic import (register_line_magic, register_cell_magic, | |
18 | register_line_cell_magic) |
|
18 | register_line_cell_magic) | |
19 |
|
19 | |||
20 | @register_line_magic |
|
20 | @register_line_magic | |
21 | def lmagic(line): |
|
21 | def lmagic(line): | |
22 | "my line magic" |
|
22 | "my line magic" | |
23 | return line |
|
23 | return line | |
24 |
|
24 | |||
25 | @register_cell_magic |
|
25 | @register_cell_magic | |
26 | def cmagic(line, cell): |
|
26 | def cmagic(line, cell): | |
27 | "my cell magic" |
|
27 | "my cell magic" | |
28 | return line, cell |
|
28 | return line, cell | |
29 |
|
29 | |||
30 | @register_line_cell_magic |
|
30 | @register_line_cell_magic | |
31 | def lcmagic(line, cell=None): |
|
31 | def lcmagic(line, cell=None): | |
32 | "Magic that works both as %lcmagic and as %%lcmagic" |
|
32 | "Magic that works both as %lcmagic and as %%lcmagic" | |
33 | if cell is None: |
|
33 | if cell is None: | |
34 | print("Called as line magic") |
|
34 | print("Called as line magic") | |
35 | return line |
|
35 | return line | |
36 | else: |
|
36 | else: | |
37 | print("Called as cell magic") |
|
37 | print("Called as cell magic") | |
38 | return line, cell |
|
38 | return line, cell | |
39 |
|
39 | |||
40 | # In an interactive session, we need to delete these to avoid |
|
40 | # In an interactive session, we need to delete these to avoid | |
41 | # name conflicts for automagic to work on line magics. |
|
41 | # name conflicts for automagic to work on line magics. | |
42 | del lmagic, lcmagic |
|
42 | del lmagic, lcmagic | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | You can also create magics of all three kinds by inheriting from the |
|
45 | You can also create magics of all three kinds by inheriting from the | |
46 | :class:`IPython.core.magic.Magics` class. This lets you create magics that can |
|
46 | :class:`IPython.core.magic.Magics` class. This lets you create magics that can | |
47 | potentially hold state in between calls, and that have full access to the main |
|
47 | potentially hold state in between calls, and that have full access to the main | |
48 | IPython object: |
|
48 | IPython object: | |
49 |
|
49 | |||
50 | .. sourcecode:: python |
|
50 | .. sourcecode:: python | |
51 |
|
51 | |||
52 | # This code can be put in any Python module, it does not require IPython |
|
52 | # This code can be put in any Python module, it does not require IPython | |
53 | # itself to be running already. It only creates the magics subclass but |
|
53 | # itself to be running already. It only creates the magics subclass but | |
54 | # doesn't instantiate it yet. |
|
54 | # doesn't instantiate it yet. | |
55 | from __future__ import print_function |
|
55 | from __future__ import print_function | |
56 | from IPython.core.magic import (Magics, magics_class, line_magic, |
|
56 | from IPython.core.magic import (Magics, magics_class, line_magic, | |
57 | cell_magic, line_cell_magic) |
|
57 | cell_magic, line_cell_magic) | |
58 |
|
58 | |||
59 | # The class MUST call this class decorator at creation time |
|
59 | # The class MUST call this class decorator at creation time | |
60 | @magics_class |
|
60 | @magics_class | |
61 | class MyMagics(Magics): |
|
61 | class MyMagics(Magics): | |
62 |
|
62 | |||
63 | @line_magic |
|
63 | @line_magic | |
64 | def lmagic(self, line): |
|
64 | def lmagic(self, line): | |
65 | "my line magic" |
|
65 | "my line magic" | |
66 | print("Full access to the main IPython object:", self.shell) |
|
66 | print("Full access to the main IPython object:", self.shell) | |
67 | print("Variables in the user namespace:", list(self.shell.user_ns.keys())) |
|
67 | print("Variables in the user namespace:", list(self.shell.user_ns.keys())) | |
68 | return line |
|
68 | return line | |
69 |
|
69 | |||
70 | @cell_magic |
|
70 | @cell_magic | |
71 | def cmagic(self, line, cell): |
|
71 | def cmagic(self, line, cell): | |
72 | "my cell magic" |
|
72 | "my cell magic" | |
73 | return line, cell |
|
73 | return line, cell | |
74 |
|
74 | |||
75 | @line_cell_magic |
|
75 | @line_cell_magic | |
76 | def lcmagic(self, line, cell=None): |
|
76 | def lcmagic(self, line, cell=None): | |
77 | "Magic that works both as %lcmagic and as %%lcmagic" |
|
77 | "Magic that works both as %lcmagic and as %%lcmagic" | |
78 | if cell is None: |
|
78 | if cell is None: | |
79 | print("Called as line magic") |
|
79 | print("Called as line magic") | |
80 | return line |
|
80 | return line | |
81 | else: |
|
81 | else: | |
82 | print("Called as cell magic") |
|
82 | print("Called as cell magic") | |
83 | return line, cell |
|
83 | return line, cell | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | # In order to actually use these magics, you must register them with a |
|
86 | # In order to actually use these magics, you must register them with a | |
87 | # running IPython. |
|
87 | # running IPython. | |
88 |
|
88 | |||
89 | def load_ipython_extension(ipython): |
|
89 | def load_ipython_extension(ipython): | |
90 | """ |
|
90 | """ | |
91 | Any module file that define a function named `load_ipython_extension` |
|
91 | Any module file that define a function named `load_ipython_extension` | |
92 | can be loaded via `%load_ext module.path` or be configured to be |
|
92 | can be loaded via `%load_ext module.path` or be configured to be | |
93 | autoloaded by IPython at startup time. |
|
93 | autoloaded by IPython at startup time. | |
94 | """ |
|
94 | """ | |
95 | # You can register the class itself without instantiating it. IPython will |
|
95 | # You can register the class itself without instantiating it. IPython will | |
96 | # call the default constructor on it. |
|
96 | # call the default constructor on it. | |
97 | ipython.register_magics(MyMagics) |
|
97 | ipython.register_magics(MyMagics) | |
98 |
|
98 | |||
99 | If you want to create a class with a different constructor that holds |
|
99 | If you want to create a class with a different constructor that holds | |
100 | additional state, then you should always call the parent constructor and |
|
100 | additional state, then you should always call the parent constructor and | |
101 | instantiate the class yourself before registration: |
|
101 | instantiate the class yourself before registration: | |
102 |
|
102 | |||
103 | .. sourcecode:: python |
|
103 | .. sourcecode:: python | |
104 |
|
104 | |||
105 | @magics_class |
|
105 | @magics_class | |
106 | class StatefulMagics(Magics): |
|
106 | class StatefulMagics(Magics): | |
107 | "Magics that hold additional state" |
|
107 | "Magics that hold additional state" | |
108 |
|
108 | |||
109 | def __init__(self, shell, data): |
|
109 | def __init__(self, shell, data): | |
110 | # You must call the parent constructor |
|
110 | # You must call the parent constructor | |
111 | super(StatefulMagics, self).__init__(shell) |
|
111 | super(StatefulMagics, self).__init__(shell) | |
112 | self.data = data |
|
112 | self.data = data | |
113 |
|
113 | |||
114 | # etc... |
|
114 | # etc... | |
115 |
|
115 | |||
116 | def load_ipython_extension(ipython): |
|
116 | def load_ipython_extension(ipython): | |
117 | """ |
|
117 | """ | |
118 | Any module file that define a function named `load_ipython_extension` |
|
118 | Any module file that define a function named `load_ipython_extension` | |
119 | can be loaded via `%load_ext module.path` or be configured to be |
|
119 | can be loaded via `%load_ext module.path` or be configured to be | |
120 | autoloaded by IPython at startup time. |
|
120 | autoloaded by IPython at startup time. | |
121 | """ |
|
121 | """ | |
122 | # This class must then be registered with a manually created instance, |
|
122 | # This class must then be registered with a manually created instance, | |
123 | # since its constructor has different arguments from the default: |
|
123 | # since its constructor has different arguments from the default: | |
124 | magics = StatefulMagics(ipython, some_data) |
|
124 | magics = StatefulMagics(ipython, some_data) | |
125 | ipython.register_magics(magics) |
|
125 | ipython.register_magics(magics) | |
126 |
|
126 | |||
127 |
|
127 | |||
128 | .. note:: |
|
128 | .. note:: | |
129 |
|
129 | |||
130 | In early IPython versions 0.12 and before the line magics were |
|
130 | In early IPython versions 0.12 and before the line magics were | |
131 | created using a :func:`define_magic` API function. This API has been |
|
131 | created using a :func:`define_magic` API function. This API has been | |
132 | replaced with the above in IPython 0.13 and then completely removed |
|
132 | replaced with the above in IPython 0.13 and then completely removed | |
133 | in IPython 5. Maintainers of IPython extensions that still use the |
|
133 | in IPython 5. Maintainers of IPython extensions that still use the | |
134 | :func:`define_magic` function are advised to adjust their code |
|
134 | :func:`define_magic` function are advised to adjust their code | |
135 | for the current API. |
|
135 | for the current API. | |
136 |
|
136 | |||
137 |
|
137 | |||
138 | Accessing user namespace and local scope |
|
138 | Accessing user namespace and local scope | |
139 | ======================================== |
|
139 | ======================================== | |
140 |
|
140 | |||
141 | When creating line magics, you may need to access surrounding scope to get user |
|
141 | When creating line magics, you may need to access surrounding scope to get user | |
142 | variables (e.g when called inside functions). IPython provides the |
|
142 | variables (e.g when called inside functions). IPython provides the | |
143 | ``@needs_local_scope`` decorator that can be imported from |
|
143 | ``@needs_local_scope`` decorator that can be imported from | |
144 |
``IPython.core.magic |
|
144 | ``IPython.core.magic``. When decorated with ``@needs_local_scope`` a magic will | |
145 | be passed ``local_ns`` as an argument. As a convenience ``@needs_local_scope`` |
|
145 | be passed ``local_ns`` as an argument. As a convenience ``@needs_local_scope`` | |
146 | can also be applied to cell magics even if cell magics cannot appear at local |
|
146 | can also be applied to cell magics even if cell magics cannot appear at local | |
147 | scope context. |
|
147 | scope context. | |
148 |
|
148 | |||
149 | Silencing the magic output |
|
149 | Silencing the magic output | |
150 | ========================== |
|
150 | ========================== | |
151 |
|
151 | |||
152 | Sometimes it may be useful to define a magic that can be silenced the same way |
|
152 | Sometimes it may be useful to define a magic that can be silenced the same way | |
153 | that non-magic expressions can, i.e., by appending a semicolon at the end of the Python |
|
153 | that non-magic expressions can, i.e., by appending a semicolon at the end of the Python | |
154 | code to be executed. That can be achieved by decorating the magic function with |
|
154 | code to be executed. That can be achieved by decorating the magic function with | |
155 | the decorator ``@output_can_be_silenced`` that can be imported from |
|
155 | the decorator ``@output_can_be_silenced`` that can be imported from | |
156 |
``IPython.core.magic |
|
156 | ``IPython.core.magic``. When this decorator is used, IPython will parse the Python | |
157 | code used by the magic and, if the last token is a ``;``, the output created by the |
|
157 | code used by the magic and, if the last token is a ``;``, the output created by the | |
158 | magic will not show up on the screen. If you want to see an example of this decorator |
|
158 | magic will not show up on the screen. If you want to see an example of this decorator | |
159 | in action, take a look on the ``time`` magic defined in |
|
159 | in action, take a look on the ``time`` magic defined in | |
160 | ``IPython.core.magics.execution.py``. |
|
160 | ``IPython.core.magics.execution.py``. | |
161 |
|
161 | |||
162 | Complete Example |
|
162 | Complete Example | |
163 | ================ |
|
163 | ================ | |
164 |
|
164 | |||
165 | Here is a full example of a magic package. You can distribute magics using |
|
165 | Here is a full example of a magic package. You can distribute magics using | |
166 | setuptools, distutils, or any other distribution tools like `flit |
|
166 | setuptools, distutils, or any other distribution tools like `flit | |
167 | <https://flit.readthedocs.io>`_ for pure Python packages. |
|
167 | <https://flit.readthedocs.io>`_ for pure Python packages. | |
168 |
|
168 | |||
169 | When distributing magics as part of a package, recommended best practice is to |
|
169 | When distributing magics as part of a package, recommended best practice is to | |
170 | execute the registration inside the `load_ipython_extension` as demonstrated in |
|
170 | execute the registration inside the `load_ipython_extension` as demonstrated in | |
171 | the example below, instead of directly in the module (as in the initial example |
|
171 | the example below, instead of directly in the module (as in the initial example | |
172 | with the ``@register_*`` decorators). This means a user will need to explicitly |
|
172 | with the ``@register_*`` decorators). This means a user will need to explicitly | |
173 | choose to load your magic with ``%load_ext``. instead implicitly getting it when |
|
173 | choose to load your magic with ``%load_ext``. instead implicitly getting it when | |
174 | importing the module. This is particularly relevant if loading your magic has |
|
174 | importing the module. This is particularly relevant if loading your magic has | |
175 | side effects, if it is slow to load, or if it might override another magic with |
|
175 | side effects, if it is slow to load, or if it might override another magic with | |
176 | the same name. |
|
176 | the same name. | |
177 |
|
177 | |||
178 | .. sourcecode:: bash |
|
178 | .. sourcecode:: bash | |
179 |
|
179 | |||
180 | . |
|
180 | . | |
181 | ├── example_magic |
|
181 | ├── example_magic | |
182 | │ ├── __init__.py |
|
182 | │ ├── __init__.py | |
183 | │ └── abracadabra.py |
|
183 | │ └── abracadabra.py | |
184 | └── setup.py |
|
184 | └── setup.py | |
185 |
|
185 | |||
186 | .. sourcecode:: bash |
|
186 | .. sourcecode:: bash | |
187 |
|
187 | |||
188 | $ cat example_magic/__init__.py |
|
188 | $ cat example_magic/__init__.py | |
189 | """An example magic""" |
|
189 | """An example magic""" | |
190 | __version__ = '0.0.1' |
|
190 | __version__ = '0.0.1' | |
191 |
|
191 | |||
192 | from .abracadabra import Abracadabra |
|
192 | from .abracadabra import Abracadabra | |
193 |
|
193 | |||
194 | def load_ipython_extension(ipython): |
|
194 | def load_ipython_extension(ipython): | |
195 | ipython.register_magics(Abracadabra) |
|
195 | ipython.register_magics(Abracadabra) | |
196 |
|
196 | |||
197 | .. sourcecode:: bash |
|
197 | .. sourcecode:: bash | |
198 |
|
198 | |||
199 | $ cat example_magic/abracadabra.py |
|
199 | $ cat example_magic/abracadabra.py | |
200 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic) |
|
200 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic) | |
201 |
|
201 | |||
202 | @magics_class |
|
202 | @magics_class | |
203 | class Abracadabra(Magics): |
|
203 | class Abracadabra(Magics): | |
204 |
|
204 | |||
205 | @line_magic |
|
205 | @line_magic | |
206 | def abra(self, line): |
|
206 | def abra(self, line): | |
207 | return line |
|
207 | return line | |
208 |
|
208 | |||
209 | @cell_magic |
|
209 | @cell_magic | |
210 | def cadabra(self, line, cell): |
|
210 | def cadabra(self, line, cell): | |
211 | return line, cell |
|
211 | return line, cell | |
212 |
|
212 |
General Comments 0
You need to be logged in to leave comments.
Login now