##// END OF EJS Templates
Merge pull request #13702 from Carreau/mdocs...
Matthias Bussonnier -
r27696:35918166 merge
parent child Browse files
Show More
@@ -1,659 +1,659 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3
3
4 import argparse
4 import argparse
5 from logging import error
5 from logging import error
6 import io
6 import io
7 import os
7 import os
8 from pprint import pformat
8 from pprint import pformat
9 import sys
9 import sys
10 from warnings import warn
10 from warnings import warn
11
11
12 from traitlets.utils.importstring import import_item
12 from traitlets.utils.importstring import import_item
13 from IPython.core import magic_arguments, page
13 from IPython.core import magic_arguments, page
14 from IPython.core.error import UsageError
14 from IPython.core.error import UsageError
15 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
15 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
16 from IPython.utils.text import format_screen, dedent, indent
16 from IPython.utils.text import format_screen, dedent, indent
17 from IPython.testing.skipdoctest import skip_doctest
17 from IPython.testing.skipdoctest import skip_doctest
18 from IPython.utils.ipstruct import Struct
18 from IPython.utils.ipstruct import Struct
19
19
20
20
21 class MagicsDisplay(object):
21 class MagicsDisplay(object):
22 def __init__(self, magics_manager, ignore=None):
22 def __init__(self, magics_manager, ignore=None):
23 self.ignore = ignore if ignore else []
23 self.ignore = ignore if ignore else []
24 self.magics_manager = magics_manager
24 self.magics_manager = magics_manager
25
25
26 def _lsmagic(self):
26 def _lsmagic(self):
27 """The main implementation of the %lsmagic"""
27 """The main implementation of the %lsmagic"""
28 mesc = magic_escapes['line']
28 mesc = magic_escapes['line']
29 cesc = magic_escapes['cell']
29 cesc = magic_escapes['cell']
30 mman = self.magics_manager
30 mman = self.magics_manager
31 magics = mman.lsmagic()
31 magics = mman.lsmagic()
32 out = ['Available line magics:',
32 out = ['Available line magics:',
33 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
33 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
34 '',
34 '',
35 'Available cell magics:',
35 'Available cell magics:',
36 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
36 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
37 '',
37 '',
38 mman.auto_status()]
38 mman.auto_status()]
39 return '\n'.join(out)
39 return '\n'.join(out)
40
40
41 def _repr_pretty_(self, p, cycle):
41 def _repr_pretty_(self, p, cycle):
42 p.text(self._lsmagic())
42 p.text(self._lsmagic())
43
43
44 def __str__(self):
44 def __str__(self):
45 return self._lsmagic()
45 return self._lsmagic()
46
46
47 def _jsonable(self):
47 def _jsonable(self):
48 """turn magics dict into jsonable dict of the same structure
48 """turn magics dict into jsonable dict of the same structure
49
49
50 replaces object instances with their class names as strings
50 replaces object instances with their class names as strings
51 """
51 """
52 magic_dict = {}
52 magic_dict = {}
53 mman = self.magics_manager
53 mman = self.magics_manager
54 magics = mman.lsmagic()
54 magics = mman.lsmagic()
55 for key, subdict in magics.items():
55 for key, subdict in magics.items():
56 d = {}
56 d = {}
57 magic_dict[key] = d
57 magic_dict[key] = d
58 for name, obj in subdict.items():
58 for name, obj in subdict.items():
59 try:
59 try:
60 classname = obj.__self__.__class__.__name__
60 classname = obj.__self__.__class__.__name__
61 except AttributeError:
61 except AttributeError:
62 classname = 'Other'
62 classname = 'Other'
63
63
64 d[name] = classname
64 d[name] = classname
65 return magic_dict
65 return magic_dict
66
66
67 def _repr_json_(self):
67 def _repr_json_(self):
68 return self._jsonable()
68 return self._jsonable()
69
69
70
70
71 @magics_class
71 @magics_class
72 class BasicMagics(Magics):
72 class BasicMagics(Magics):
73 """Magics that provide central IPython functionality.
73 """Magics that provide central IPython functionality.
74
74
75 These are various magics that don't fit into specific categories but that
75 These are various magics that don't fit into specific categories but that
76 are all part of the base 'IPython experience'."""
76 are all part of the base 'IPython experience'."""
77
77
78 @skip_doctest
78 @skip_doctest
79 @magic_arguments.magic_arguments()
79 @magic_arguments.magic_arguments()
80 @magic_arguments.argument(
80 @magic_arguments.argument(
81 '-l', '--line', action='store_true',
81 '-l', '--line', action='store_true',
82 help="""Create a line magic alias."""
82 help="""Create a line magic alias."""
83 )
83 )
84 @magic_arguments.argument(
84 @magic_arguments.argument(
85 '-c', '--cell', action='store_true',
85 '-c', '--cell', action='store_true',
86 help="""Create a cell magic alias."""
86 help="""Create a cell magic alias."""
87 )
87 )
88 @magic_arguments.argument(
88 @magic_arguments.argument(
89 'name',
89 'name',
90 help="""Name of the magic to be created."""
90 help="""Name of the magic to be created."""
91 )
91 )
92 @magic_arguments.argument(
92 @magic_arguments.argument(
93 'target',
93 'target',
94 help="""Name of the existing line or cell magic."""
94 help="""Name of the existing line or cell magic."""
95 )
95 )
96 @magic_arguments.argument(
96 @magic_arguments.argument(
97 '-p', '--params', default=None,
97 '-p', '--params', default=None,
98 help="""Parameters passed to the magic function."""
98 help="""Parameters passed to the magic function."""
99 )
99 )
100 @line_magic
100 @line_magic
101 def alias_magic(self, line=''):
101 def alias_magic(self, line=''):
102 """Create an alias for an existing line or cell magic.
102 """Create an alias for an existing line or cell magic.
103
103
104 Examples
104 Examples
105 --------
105 --------
106 ::
106 ::
107
107
108 In [1]: %alias_magic t timeit
108 In [1]: %alias_magic t timeit
109 Created `%t` as an alias for `%timeit`.
109 Created `%t` as an alias for `%timeit`.
110 Created `%%t` as an alias for `%%timeit`.
110 Created `%%t` as an alias for `%%timeit`.
111
111
112 In [2]: %t -n1 pass
112 In [2]: %t -n1 pass
113 1 loops, best of 3: 954 ns per loop
113 1 loops, best of 3: 954 ns per loop
114
114
115 In [3]: %%t -n1
115 In [3]: %%t -n1
116 ...: pass
116 ...: pass
117 ...:
117 ...:
118 1 loops, best of 3: 954 ns per loop
118 1 loops, best of 3: 954 ns per loop
119
119
120 In [4]: %alias_magic --cell whereami pwd
120 In [4]: %alias_magic --cell whereami pwd
121 UsageError: Cell magic function `%%pwd` not found.
121 UsageError: Cell magic function `%%pwd` not found.
122 In [5]: %alias_magic --line whereami pwd
122 In [5]: %alias_magic --line whereami pwd
123 Created `%whereami` as an alias for `%pwd`.
123 Created `%whereami` as an alias for `%pwd`.
124
124
125 In [6]: %whereami
125 In [6]: %whereami
126 Out[6]: u'/home/testuser'
126 Out[6]: u'/home/testuser'
127
127
128 In [7]: %alias_magic h history "-p -l 30" --line
128 In [7]: %alias_magic h history "-p -l 30" --line
129 Created `%h` as an alias for `%history -l 30`.
129 Created `%h` as an alias for `%history -l 30`.
130 """
130 """
131
131
132 args = magic_arguments.parse_argstring(self.alias_magic, line)
132 args = magic_arguments.parse_argstring(self.alias_magic, line)
133 shell = self.shell
133 shell = self.shell
134 mman = self.shell.magics_manager
134 mman = self.shell.magics_manager
135 escs = ''.join(magic_escapes.values())
135 escs = ''.join(magic_escapes.values())
136
136
137 target = args.target.lstrip(escs)
137 target = args.target.lstrip(escs)
138 name = args.name.lstrip(escs)
138 name = args.name.lstrip(escs)
139
139
140 params = args.params
140 params = args.params
141 if (params and
141 if (params and
142 ((params.startswith('"') and params.endswith('"'))
142 ((params.startswith('"') and params.endswith('"'))
143 or (params.startswith("'") and params.endswith("'")))):
143 or (params.startswith("'") and params.endswith("'")))):
144 params = params[1:-1]
144 params = params[1:-1]
145
145
146 # Find the requested magics.
146 # Find the requested magics.
147 m_line = shell.find_magic(target, 'line')
147 m_line = shell.find_magic(target, 'line')
148 m_cell = shell.find_magic(target, 'cell')
148 m_cell = shell.find_magic(target, 'cell')
149 if args.line and m_line is None:
149 if args.line and m_line is None:
150 raise UsageError('Line magic function `%s%s` not found.' %
150 raise UsageError('Line magic function `%s%s` not found.' %
151 (magic_escapes['line'], target))
151 (magic_escapes['line'], target))
152 if args.cell and m_cell is None:
152 if args.cell and m_cell is None:
153 raise UsageError('Cell magic function `%s%s` not found.' %
153 raise UsageError('Cell magic function `%s%s` not found.' %
154 (magic_escapes['cell'], target))
154 (magic_escapes['cell'], target))
155
155
156 # If --line and --cell are not specified, default to the ones
156 # If --line and --cell are not specified, default to the ones
157 # that are available.
157 # that are available.
158 if not args.line and not args.cell:
158 if not args.line and not args.cell:
159 if not m_line and not m_cell:
159 if not m_line and not m_cell:
160 raise UsageError(
160 raise UsageError(
161 'No line or cell magic with name `%s` found.' % target
161 'No line or cell magic with name `%s` found.' % target
162 )
162 )
163 args.line = bool(m_line)
163 args.line = bool(m_line)
164 args.cell = bool(m_cell)
164 args.cell = bool(m_cell)
165
165
166 params_str = "" if params is None else " " + params
166 params_str = "" if params is None else " " + params
167
167
168 if args.line:
168 if args.line:
169 mman.register_alias(name, target, 'line', params)
169 mman.register_alias(name, target, 'line', params)
170 print('Created `%s%s` as an alias for `%s%s%s`.' % (
170 print('Created `%s%s` as an alias for `%s%s%s`.' % (
171 magic_escapes['line'], name,
171 magic_escapes['line'], name,
172 magic_escapes['line'], target, params_str))
172 magic_escapes['line'], target, params_str))
173
173
174 if args.cell:
174 if args.cell:
175 mman.register_alias(name, target, 'cell', params)
175 mman.register_alias(name, target, 'cell', params)
176 print('Created `%s%s` as an alias for `%s%s%s`.' % (
176 print('Created `%s%s` as an alias for `%s%s%s`.' % (
177 magic_escapes['cell'], name,
177 magic_escapes['cell'], name,
178 magic_escapes['cell'], target, params_str))
178 magic_escapes['cell'], target, params_str))
179
179
180 @line_magic
180 @line_magic
181 def lsmagic(self, parameter_s=''):
181 def lsmagic(self, parameter_s=''):
182 """List currently available magic functions."""
182 """List currently available magic functions."""
183 return MagicsDisplay(self.shell.magics_manager, ignore=[])
183 return MagicsDisplay(self.shell.magics_manager, ignore=[])
184
184
185 def _magic_docs(self, brief=False, rest=False):
185 def _magic_docs(self, brief=False, rest=False):
186 """Return docstrings from magic functions."""
186 """Return docstrings from magic functions."""
187 mman = self.shell.magics_manager
187 mman = self.shell.magics_manager
188 docs = mman.lsmagic_docs(brief, missing='No documentation')
188 docs = mman.lsmagic_docs(brief, missing='No documentation')
189
189
190 if rest:
190 if rest:
191 format_string = '**%s%s**::\n\n%s\n\n'
191 format_string = '**%s%s**::\n\n%s\n\n'
192 else:
192 else:
193 format_string = '%s%s:\n%s\n'
193 format_string = '%s%s:\n%s\n'
194
194
195 return ''.join(
195 return ''.join(
196 [format_string % (magic_escapes['line'], fname,
196 [format_string % (magic_escapes['line'], fname,
197 indent(dedent(fndoc)))
197 indent(dedent(fndoc)))
198 for fname, fndoc in sorted(docs['line'].items())]
198 for fname, fndoc in sorted(docs['line'].items())]
199 +
199 +
200 [format_string % (magic_escapes['cell'], fname,
200 [format_string % (magic_escapes['cell'], fname,
201 indent(dedent(fndoc)))
201 indent(dedent(fndoc)))
202 for fname, fndoc in sorted(docs['cell'].items())]
202 for fname, fndoc in sorted(docs['cell'].items())]
203 )
203 )
204
204
205 @line_magic
205 @line_magic
206 def magic(self, parameter_s=''):
206 def magic(self, parameter_s=''):
207 """Print information about the magic function system.
207 """Print information about the magic function system.
208
208
209 Supported formats: -latex, -brief, -rest
209 Supported formats: -latex, -brief, -rest
210 """
210 """
211
211
212 mode = ''
212 mode = ''
213 try:
213 try:
214 mode = parameter_s.split()[0][1:]
214 mode = parameter_s.split()[0][1:]
215 except IndexError:
215 except IndexError:
216 pass
216 pass
217
217
218 brief = (mode == 'brief')
218 brief = (mode == 'brief')
219 rest = (mode == 'rest')
219 rest = (mode == 'rest')
220 magic_docs = self._magic_docs(brief, rest)
220 magic_docs = self._magic_docs(brief, rest)
221
221
222 if mode == 'latex':
222 if mode == 'latex':
223 print(self.format_latex(magic_docs))
223 print(self.format_latex(magic_docs))
224 return
224 return
225 else:
225 else:
226 magic_docs = format_screen(magic_docs)
226 magic_docs = format_screen(magic_docs)
227
227
228 out = ["""
228 out = ["""
229 IPython's 'magic' functions
229 IPython's 'magic' functions
230 ===========================
230 ===========================
231
231
232 The magic function system provides a series of functions which allow you to
232 The magic function system provides a series of functions which allow you to
233 control the behavior of IPython itself, plus a lot of system-type
233 control the behavior of IPython itself, plus a lot of system-type
234 features. There are two kinds of magics, line-oriented and cell-oriented.
234 features. There are two kinds of magics, line-oriented and cell-oriented.
235
235
236 Line magics are prefixed with the % character and work much like OS
236 Line magics are prefixed with the % character and work much like OS
237 command-line calls: they get as an argument the rest of the line, where
237 command-line calls: they get as an argument the rest of the line, where
238 arguments are passed without parentheses or quotes. For example, this will
238 arguments are passed without parentheses or quotes. For example, this will
239 time the given statement::
239 time the given statement::
240
240
241 %timeit range(1000)
241 %timeit range(1000)
242
242
243 Cell magics are prefixed with a double %%, and they are functions that get as
243 Cell magics are prefixed with a double %%, and they are functions that get as
244 an argument not only the rest of the line, but also the lines below it in a
244 an argument not only the rest of the line, but also the lines below it in a
245 separate argument. These magics are called with two arguments: the rest of the
245 separate argument. These magics are called with two arguments: the rest of the
246 call line and the body of the cell, consisting of the lines below the first.
246 call line and the body of the cell, consisting of the lines below the first.
247 For example::
247 For example::
248
248
249 %%timeit x = numpy.random.randn((100, 100))
249 %%timeit x = numpy.random.randn((100, 100))
250 numpy.linalg.svd(x)
250 numpy.linalg.svd(x)
251
251
252 will time the execution of the numpy svd routine, running the assignment of x
252 will time the execution of the numpy svd routine, running the assignment of x
253 as part of the setup phase, which is not timed.
253 as part of the setup phase, which is not timed.
254
254
255 In a line-oriented client (the terminal or Qt console IPython), starting a new
255 In a line-oriented client (the terminal or Qt console IPython), starting a new
256 input with %% will automatically enter cell mode, and IPython will continue
256 input with %% will automatically enter cell mode, and IPython will continue
257 reading input until a blank line is given. In the notebook, simply type the
257 reading input until a blank line is given. In the notebook, simply type the
258 whole cell as one entity, but keep in mind that the %% escape can only be at
258 whole cell as one entity, but keep in mind that the %% escape can only be at
259 the very start of the cell.
259 the very start of the cell.
260
260
261 NOTE: If you have 'automagic' enabled (via the command line option or with the
261 NOTE: If you have 'automagic' enabled (via the command line option or with the
262 %automagic function), you don't need to type in the % explicitly for line
262 %automagic function), you don't need to type in the % explicitly for line
263 magics; cell magics always require an explicit '%%' escape. By default,
263 magics; cell magics always require an explicit '%%' escape. By default,
264 IPython ships with automagic on, so you should only rarely need the % escape.
264 IPython ships with automagic on, so you should only rarely need the % escape.
265
265
266 Example: typing '%cd mydir' (without the quotes) changes your working directory
266 Example: typing '%cd mydir' (without the quotes) changes your working directory
267 to 'mydir', if it exists.
267 to 'mydir', if it exists.
268
268
269 For a list of the available magic functions, use %lsmagic. For a description
269 For a list of the available magic functions, use %lsmagic. For a description
270 of any of them, type %magic_name?, e.g. '%cd?'.
270 of any of them, type %magic_name?, e.g. '%cd?'.
271
271
272 Currently the magic system has the following functions:""",
272 Currently the magic system has the following functions:""",
273 magic_docs,
273 magic_docs,
274 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
274 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
275 str(self.lsmagic()),
275 str(self.lsmagic()),
276 ]
276 ]
277 page.page('\n'.join(out))
277 page.page('\n'.join(out))
278
278
279
279
280 @line_magic
280 @line_magic
281 def page(self, parameter_s=''):
281 def page(self, parameter_s=''):
282 """Pretty print the object and display it through a pager.
282 """Pretty print the object and display it through a pager.
283
283
284 %page [options] OBJECT
284 %page [options] OBJECT
285
285
286 If no object is given, use _ (last output).
286 If no object is given, use _ (last output).
287
287
288 Options:
288 Options:
289
289
290 -r: page str(object), don't pretty-print it."""
290 -r: page str(object), don't pretty-print it."""
291
291
292 # After a function contributed by Olivier Aubert, slightly modified.
292 # After a function contributed by Olivier Aubert, slightly modified.
293
293
294 # Process options/args
294 # Process options/args
295 opts, args = self.parse_options(parameter_s, 'r')
295 opts, args = self.parse_options(parameter_s, 'r')
296 raw = 'r' in opts
296 raw = 'r' in opts
297
297
298 oname = args and args or '_'
298 oname = args and args or '_'
299 info = self.shell._ofind(oname)
299 info = self.shell._ofind(oname)
300 if info['found']:
300 if info['found']:
301 txt = (raw and str or pformat)( info['obj'] )
301 txt = (raw and str or pformat)( info['obj'] )
302 page.page(txt)
302 page.page(txt)
303 else:
303 else:
304 print('Object `%s` not found' % oname)
304 print('Object `%s` not found' % oname)
305
305
306 @line_magic
306 @line_magic
307 def pprint(self, parameter_s=''):
307 def pprint(self, parameter_s=''):
308 """Toggle pretty printing on/off."""
308 """Toggle pretty printing on/off."""
309 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 ptformatter = self.shell.display_formatter.formatters['text/plain']
310 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 ptformatter.pprint = bool(1 - ptformatter.pprint)
311 print('Pretty printing has been turned',
311 print('Pretty printing has been turned',
312 ['OFF','ON'][ptformatter.pprint])
312 ['OFF','ON'][ptformatter.pprint])
313
313
314 @line_magic
314 @line_magic
315 def colors(self, parameter_s=''):
315 def colors(self, parameter_s=''):
316 """Switch color scheme for prompts, info system and exception handlers.
316 """Switch color scheme for prompts, info system and exception handlers.
317
317
318 Currently implemented schemes: NoColor, Linux, LightBG.
318 Currently implemented schemes: NoColor, Linux, LightBG.
319
319
320 Color scheme names are not case-sensitive.
320 Color scheme names are not case-sensitive.
321
321
322 Examples
322 Examples
323 --------
323 --------
324 To get a plain black and white terminal::
324 To get a plain black and white terminal::
325
325
326 %colors nocolor
326 %colors nocolor
327 """
327 """
328 def color_switch_err(name):
328 def color_switch_err(name):
329 warn('Error changing %s color schemes.\n%s' %
329 warn('Error changing %s color schemes.\n%s' %
330 (name, sys.exc_info()[1]), stacklevel=2)
330 (name, sys.exc_info()[1]), stacklevel=2)
331
331
332
332
333 new_scheme = parameter_s.strip()
333 new_scheme = parameter_s.strip()
334 if not new_scheme:
334 if not new_scheme:
335 raise UsageError(
335 raise UsageError(
336 "%colors: you must specify a color scheme. See '%colors?'")
336 "%colors: you must specify a color scheme. See '%colors?'")
337 # local shortcut
337 # local shortcut
338 shell = self.shell
338 shell = self.shell
339
339
340 # Set shell colour scheme
340 # Set shell colour scheme
341 try:
341 try:
342 shell.colors = new_scheme
342 shell.colors = new_scheme
343 shell.refresh_style()
343 shell.refresh_style()
344 except:
344 except:
345 color_switch_err('shell')
345 color_switch_err('shell')
346
346
347 # Set exception colors
347 # Set exception colors
348 try:
348 try:
349 shell.InteractiveTB.set_colors(scheme = new_scheme)
349 shell.InteractiveTB.set_colors(scheme = new_scheme)
350 shell.SyntaxTB.set_colors(scheme = new_scheme)
350 shell.SyntaxTB.set_colors(scheme = new_scheme)
351 except:
351 except:
352 color_switch_err('exception')
352 color_switch_err('exception')
353
353
354 # Set info (for 'object?') colors
354 # Set info (for 'object?') colors
355 if shell.color_info:
355 if shell.color_info:
356 try:
356 try:
357 shell.inspector.set_active_scheme(new_scheme)
357 shell.inspector.set_active_scheme(new_scheme)
358 except:
358 except:
359 color_switch_err('object inspector')
359 color_switch_err('object inspector')
360 else:
360 else:
361 shell.inspector.set_active_scheme('NoColor')
361 shell.inspector.set_active_scheme('NoColor')
362
362
363 @line_magic
363 @line_magic
364 def xmode(self, parameter_s=''):
364 def xmode(self, parameter_s=''):
365 """Switch modes for the exception handlers.
365 """Switch modes for the exception handlers.
366
366
367 Valid modes: Plain, Context, Verbose, and Minimal.
367 Valid modes: Plain, Context, Verbose, and Minimal.
368
368
369 If called without arguments, acts as a toggle.
369 If called without arguments, acts as a toggle.
370
370
371 When in verbose mode the value --show (and --hide)
371 When in verbose mode the value `--show` (and `--hide`)
372 will respectively show (or hide) frames with ``__tracebackhide__ =
372 will respectively show (or hide) frames with ``__tracebackhide__ =
373 True`` value set.
373 True`` value set.
374 """
374 """
375
375
376 def xmode_switch_err(name):
376 def xmode_switch_err(name):
377 warn('Error changing %s exception modes.\n%s' %
377 warn('Error changing %s exception modes.\n%s' %
378 (name,sys.exc_info()[1]))
378 (name,sys.exc_info()[1]))
379
379
380 shell = self.shell
380 shell = self.shell
381 if parameter_s.strip() == "--show":
381 if parameter_s.strip() == "--show":
382 shell.InteractiveTB.skip_hidden = False
382 shell.InteractiveTB.skip_hidden = False
383 return
383 return
384 if parameter_s.strip() == "--hide":
384 if parameter_s.strip() == "--hide":
385 shell.InteractiveTB.skip_hidden = True
385 shell.InteractiveTB.skip_hidden = True
386 return
386 return
387
387
388 new_mode = parameter_s.strip().capitalize()
388 new_mode = parameter_s.strip().capitalize()
389 try:
389 try:
390 shell.InteractiveTB.set_mode(mode=new_mode)
390 shell.InteractiveTB.set_mode(mode=new_mode)
391 print('Exception reporting mode:',shell.InteractiveTB.mode)
391 print('Exception reporting mode:',shell.InteractiveTB.mode)
392 except:
392 except:
393 xmode_switch_err('user')
393 xmode_switch_err('user')
394
394
395 @line_magic
395 @line_magic
396 def quickref(self, arg):
396 def quickref(self, arg):
397 """ Show a quick reference sheet """
397 """ Show a quick reference sheet """
398 from IPython.core.usage import quick_reference
398 from IPython.core.usage import quick_reference
399 qr = quick_reference + self._magic_docs(brief=True)
399 qr = quick_reference + self._magic_docs(brief=True)
400 page.page(qr)
400 page.page(qr)
401
401
402 @line_magic
402 @line_magic
403 def doctest_mode(self, parameter_s=''):
403 def doctest_mode(self, parameter_s=''):
404 """Toggle doctest mode on and off.
404 """Toggle doctest mode on and off.
405
405
406 This mode is intended to make IPython behave as much as possible like a
406 This mode is intended to make IPython behave as much as possible like a
407 plain Python shell, from the perspective of how its prompts, exceptions
407 plain Python shell, from the perspective of how its prompts, exceptions
408 and output look. This makes it easy to copy and paste parts of a
408 and output look. This makes it easy to copy and paste parts of a
409 session into doctests. It does so by:
409 session into doctests. It does so by:
410
410
411 - Changing the prompts to the classic ``>>>`` ones.
411 - Changing the prompts to the classic ``>>>`` ones.
412 - Changing the exception reporting mode to 'Plain'.
412 - Changing the exception reporting mode to 'Plain'.
413 - Disabling pretty-printing of output.
413 - Disabling pretty-printing of output.
414
414
415 Note that IPython also supports the pasting of code snippets that have
415 Note that IPython also supports the pasting of code snippets that have
416 leading '>>>' and '...' prompts in them. This means that you can paste
416 leading '>>>' and '...' prompts in them. This means that you can paste
417 doctests from files or docstrings (even if they have leading
417 doctests from files or docstrings (even if they have leading
418 whitespace), and the code will execute correctly. You can then use
418 whitespace), and the code will execute correctly. You can then use
419 '%history -t' to see the translated history; this will give you the
419 '%history -t' to see the translated history; this will give you the
420 input after removal of all the leading prompts and whitespace, which
420 input after removal of all the leading prompts and whitespace, which
421 can be pasted back into an editor.
421 can be pasted back into an editor.
422
422
423 With these features, you can switch into this mode easily whenever you
423 With these features, you can switch into this mode easily whenever you
424 need to do testing and changes to doctests, without having to leave
424 need to do testing and changes to doctests, without having to leave
425 your existing IPython session.
425 your existing IPython session.
426 """
426 """
427
427
428 # Shorthands
428 # Shorthands
429 shell = self.shell
429 shell = self.shell
430 meta = shell.meta
430 meta = shell.meta
431 disp_formatter = self.shell.display_formatter
431 disp_formatter = self.shell.display_formatter
432 ptformatter = disp_formatter.formatters['text/plain']
432 ptformatter = disp_formatter.formatters['text/plain']
433 # dstore is a data store kept in the instance metadata bag to track any
433 # dstore is a data store kept in the instance metadata bag to track any
434 # changes we make, so we can undo them later.
434 # changes we make, so we can undo them later.
435 dstore = meta.setdefault('doctest_mode',Struct())
435 dstore = meta.setdefault('doctest_mode',Struct())
436 save_dstore = dstore.setdefault
436 save_dstore = dstore.setdefault
437
437
438 # save a few values we'll need to recover later
438 # save a few values we'll need to recover later
439 mode = save_dstore('mode',False)
439 mode = save_dstore('mode',False)
440 save_dstore('rc_pprint',ptformatter.pprint)
440 save_dstore('rc_pprint',ptformatter.pprint)
441 save_dstore('xmode',shell.InteractiveTB.mode)
441 save_dstore('xmode',shell.InteractiveTB.mode)
442 save_dstore('rc_separate_out',shell.separate_out)
442 save_dstore('rc_separate_out',shell.separate_out)
443 save_dstore('rc_separate_out2',shell.separate_out2)
443 save_dstore('rc_separate_out2',shell.separate_out2)
444 save_dstore('rc_separate_in',shell.separate_in)
444 save_dstore('rc_separate_in',shell.separate_in)
445 save_dstore('rc_active_types',disp_formatter.active_types)
445 save_dstore('rc_active_types',disp_formatter.active_types)
446
446
447 if not mode:
447 if not mode:
448 # turn on
448 # turn on
449
449
450 # Prompt separators like plain python
450 # Prompt separators like plain python
451 shell.separate_in = ''
451 shell.separate_in = ''
452 shell.separate_out = ''
452 shell.separate_out = ''
453 shell.separate_out2 = ''
453 shell.separate_out2 = ''
454
454
455
455
456 ptformatter.pprint = False
456 ptformatter.pprint = False
457 disp_formatter.active_types = ['text/plain']
457 disp_formatter.active_types = ['text/plain']
458
458
459 shell.magic('xmode Plain')
459 shell.magic('xmode Plain')
460 else:
460 else:
461 # turn off
461 # turn off
462 shell.separate_in = dstore.rc_separate_in
462 shell.separate_in = dstore.rc_separate_in
463
463
464 shell.separate_out = dstore.rc_separate_out
464 shell.separate_out = dstore.rc_separate_out
465 shell.separate_out2 = dstore.rc_separate_out2
465 shell.separate_out2 = dstore.rc_separate_out2
466
466
467 ptformatter.pprint = dstore.rc_pprint
467 ptformatter.pprint = dstore.rc_pprint
468 disp_formatter.active_types = dstore.rc_active_types
468 disp_formatter.active_types = dstore.rc_active_types
469
469
470 shell.magic('xmode ' + dstore.xmode)
470 shell.magic('xmode ' + dstore.xmode)
471
471
472 # mode here is the state before we switch; switch_doctest_mode takes
472 # mode here is the state before we switch; switch_doctest_mode takes
473 # the mode we're switching to.
473 # the mode we're switching to.
474 shell.switch_doctest_mode(not mode)
474 shell.switch_doctest_mode(not mode)
475
475
476 # Store new mode and inform
476 # Store new mode and inform
477 dstore.mode = bool(not mode)
477 dstore.mode = bool(not mode)
478 mode_label = ['OFF','ON'][dstore.mode]
478 mode_label = ['OFF','ON'][dstore.mode]
479 print('Doctest mode is:', mode_label)
479 print('Doctest mode is:', mode_label)
480
480
481 @line_magic
481 @line_magic
482 def gui(self, parameter_s=''):
482 def gui(self, parameter_s=''):
483 """Enable or disable IPython GUI event loop integration.
483 """Enable or disable IPython GUI event loop integration.
484
484
485 %gui [GUINAME]
485 %gui [GUINAME]
486
486
487 This magic replaces IPython's threaded shells that were activated
487 This magic replaces IPython's threaded shells that were activated
488 using the (pylab/wthread/etc.) command line flags. GUI toolkits
488 using the (pylab/wthread/etc.) command line flags. GUI toolkits
489 can now be enabled at runtime and keyboard
489 can now be enabled at runtime and keyboard
490 interrupts should work without any problems. The following toolkits
490 interrupts should work without any problems. The following toolkits
491 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
491 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
492
492
493 %gui wx # enable wxPython event loop integration
493 %gui wx # enable wxPython event loop integration
494 %gui qt4|qt # enable PyQt4 event loop integration
494 %gui qt4|qt # enable PyQt4 event loop integration
495 %gui qt5 # enable PyQt5 event loop integration
495 %gui qt5 # enable PyQt5 event loop integration
496 %gui gtk # enable PyGTK event loop integration
496 %gui gtk # enable PyGTK event loop integration
497 %gui gtk3 # enable Gtk3 event loop integration
497 %gui gtk3 # enable Gtk3 event loop integration
498 %gui gtk4 # enable Gtk4 event loop integration
498 %gui gtk4 # enable Gtk4 event loop integration
499 %gui tk # enable Tk event loop integration
499 %gui tk # enable Tk event loop integration
500 %gui osx # enable Cocoa event loop integration
500 %gui osx # enable Cocoa event loop integration
501 # (requires %matplotlib 1.1)
501 # (requires %matplotlib 1.1)
502 %gui # disable all event loop integration
502 %gui # disable all event loop integration
503
503
504 WARNING: after any of these has been called you can simply create
504 WARNING: after any of these has been called you can simply create
505 an application object, but DO NOT start the event loop yourself, as
505 an application object, but DO NOT start the event loop yourself, as
506 we have already handled that.
506 we have already handled that.
507 """
507 """
508 opts, arg = self.parse_options(parameter_s, '')
508 opts, arg = self.parse_options(parameter_s, '')
509 if arg=='': arg = None
509 if arg=='': arg = None
510 try:
510 try:
511 return self.shell.enable_gui(arg)
511 return self.shell.enable_gui(arg)
512 except Exception as e:
512 except Exception as e:
513 # print simple error message, rather than traceback if we can't
513 # print simple error message, rather than traceback if we can't
514 # hook up the GUI
514 # hook up the GUI
515 error(str(e))
515 error(str(e))
516
516
517 @skip_doctest
517 @skip_doctest
518 @line_magic
518 @line_magic
519 def precision(self, s=''):
519 def precision(self, s=''):
520 """Set floating point precision for pretty printing.
520 """Set floating point precision for pretty printing.
521
521
522 Can set either integer precision or a format string.
522 Can set either integer precision or a format string.
523
523
524 If numpy has been imported and precision is an int,
524 If numpy has been imported and precision is an int,
525 numpy display precision will also be set, via ``numpy.set_printoptions``.
525 numpy display precision will also be set, via ``numpy.set_printoptions``.
526
526
527 If no argument is given, defaults will be restored.
527 If no argument is given, defaults will be restored.
528
528
529 Examples
529 Examples
530 --------
530 --------
531 ::
531 ::
532
532
533 In [1]: from math import pi
533 In [1]: from math import pi
534
534
535 In [2]: %precision 3
535 In [2]: %precision 3
536 Out[2]: u'%.3f'
536 Out[2]: u'%.3f'
537
537
538 In [3]: pi
538 In [3]: pi
539 Out[3]: 3.142
539 Out[3]: 3.142
540
540
541 In [4]: %precision %i
541 In [4]: %precision %i
542 Out[4]: u'%i'
542 Out[4]: u'%i'
543
543
544 In [5]: pi
544 In [5]: pi
545 Out[5]: 3
545 Out[5]: 3
546
546
547 In [6]: %precision %e
547 In [6]: %precision %e
548 Out[6]: u'%e'
548 Out[6]: u'%e'
549
549
550 In [7]: pi**10
550 In [7]: pi**10
551 Out[7]: 9.364805e+04
551 Out[7]: 9.364805e+04
552
552
553 In [8]: %precision
553 In [8]: %precision
554 Out[8]: u'%r'
554 Out[8]: u'%r'
555
555
556 In [9]: pi**10
556 In [9]: pi**10
557 Out[9]: 93648.047476082982
557 Out[9]: 93648.047476082982
558 """
558 """
559 ptformatter = self.shell.display_formatter.formatters['text/plain']
559 ptformatter = self.shell.display_formatter.formatters['text/plain']
560 ptformatter.float_precision = s
560 ptformatter.float_precision = s
561 return ptformatter.float_format
561 return ptformatter.float_format
562
562
563 @magic_arguments.magic_arguments()
563 @magic_arguments.magic_arguments()
564 @magic_arguments.argument(
564 @magic_arguments.argument(
565 'filename', type=str,
565 'filename', type=str,
566 help='Notebook name or filename'
566 help='Notebook name or filename'
567 )
567 )
568 @line_magic
568 @line_magic
569 def notebook(self, s):
569 def notebook(self, s):
570 """Export and convert IPython notebooks.
570 """Export and convert IPython notebooks.
571
571
572 This function can export the current IPython history to a notebook file.
572 This function can export the current IPython history to a notebook file.
573 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
573 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
574 """
574 """
575 args = magic_arguments.parse_argstring(self.notebook, s)
575 args = magic_arguments.parse_argstring(self.notebook, s)
576 outfname = os.path.expanduser(args.filename)
576 outfname = os.path.expanduser(args.filename)
577
577
578 from nbformat import write, v4
578 from nbformat import write, v4
579
579
580 cells = []
580 cells = []
581 hist = list(self.shell.history_manager.get_range())
581 hist = list(self.shell.history_manager.get_range())
582 if(len(hist)<=1):
582 if(len(hist)<=1):
583 raise ValueError('History is empty, cannot export')
583 raise ValueError('History is empty, cannot export')
584 for session, execution_count, source in hist[:-1]:
584 for session, execution_count, source in hist[:-1]:
585 cells.append(v4.new_code_cell(
585 cells.append(v4.new_code_cell(
586 execution_count=execution_count,
586 execution_count=execution_count,
587 source=source
587 source=source
588 ))
588 ))
589 nb = v4.new_notebook(cells=cells)
589 nb = v4.new_notebook(cells=cells)
590 with io.open(outfname, "w", encoding="utf-8") as f:
590 with io.open(outfname, "w", encoding="utf-8") as f:
591 write(nb, f, version=4)
591 write(nb, f, version=4)
592
592
593 @magics_class
593 @magics_class
594 class AsyncMagics(BasicMagics):
594 class AsyncMagics(BasicMagics):
595
595
596 @line_magic
596 @line_magic
597 def autoawait(self, parameter_s):
597 def autoawait(self, parameter_s):
598 """
598 """
599 Allow to change the status of the autoawait option.
599 Allow to change the status of the autoawait option.
600
600
601 This allow you to set a specific asynchronous code runner.
601 This allow you to set a specific asynchronous code runner.
602
602
603 If no value is passed, print the currently used asynchronous integration
603 If no value is passed, print the currently used asynchronous integration
604 and whether it is activated.
604 and whether it is activated.
605
605
606 It can take a number of value evaluated in the following order:
606 It can take a number of value evaluated in the following order:
607
607
608 - False/false/off deactivate autoawait integration
608 - False/false/off deactivate autoawait integration
609 - True/true/on activate autoawait integration using configured default
609 - True/true/on activate autoawait integration using configured default
610 loop
610 loop
611 - asyncio/curio/trio activate autoawait integration and use integration
611 - asyncio/curio/trio activate autoawait integration and use integration
612 with said library.
612 with said library.
613
613
614 - `sync` turn on the pseudo-sync integration (mostly used for
614 - `sync` turn on the pseudo-sync integration (mostly used for
615 `IPython.embed()` which does not run IPython with a real eventloop and
615 `IPython.embed()` which does not run IPython with a real eventloop and
616 deactivate running asynchronous code. Turning on Asynchronous code with
616 deactivate running asynchronous code. Turning on Asynchronous code with
617 the pseudo sync loop is undefined behavior and may lead IPython to crash.
617 the pseudo sync loop is undefined behavior and may lead IPython to crash.
618
618
619 If the passed parameter does not match any of the above and is a python
619 If the passed parameter does not match any of the above and is a python
620 identifier, get said object from user namespace and set it as the
620 identifier, get said object from user namespace and set it as the
621 runner, and activate autoawait.
621 runner, and activate autoawait.
622
622
623 If the object is a fully qualified object name, attempt to import it and
623 If the object is a fully qualified object name, attempt to import it and
624 set it as the runner, and activate autoawait.
624 set it as the runner, and activate autoawait.
625
625
626 The exact behavior of autoawait is experimental and subject to change
626 The exact behavior of autoawait is experimental and subject to change
627 across version of IPython and Python.
627 across version of IPython and Python.
628 """
628 """
629
629
630 param = parameter_s.strip()
630 param = parameter_s.strip()
631 d = {True: "on", False: "off"}
631 d = {True: "on", False: "off"}
632
632
633 if not param:
633 if not param:
634 print("IPython autoawait is `{}`, and set to use `{}`".format(
634 print("IPython autoawait is `{}`, and set to use `{}`".format(
635 d[self.shell.autoawait],
635 d[self.shell.autoawait],
636 self.shell.loop_runner
636 self.shell.loop_runner
637 ))
637 ))
638 return None
638 return None
639
639
640 if param.lower() in ('false', 'off'):
640 if param.lower() in ('false', 'off'):
641 self.shell.autoawait = False
641 self.shell.autoawait = False
642 return None
642 return None
643 if param.lower() in ('true', 'on'):
643 if param.lower() in ('true', 'on'):
644 self.shell.autoawait = True
644 self.shell.autoawait = True
645 return None
645 return None
646
646
647 if param in self.shell.loop_runner_map:
647 if param in self.shell.loop_runner_map:
648 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
648 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
649 return None
649 return None
650
650
651 if param in self.shell.user_ns :
651 if param in self.shell.user_ns :
652 self.shell.loop_runner = self.shell.user_ns[param]
652 self.shell.loop_runner = self.shell.user_ns[param]
653 self.shell.autoawait = True
653 self.shell.autoawait = True
654 return None
654 return None
655
655
656 runner = import_item(param)
656 runner = import_item(param)
657
657
658 self.shell.loop_runner = runner
658 self.shell.loop_runner = runner
659 self.shell.autoawait = True
659 self.shell.autoawait = True
@@ -1,567 +1,576 b''
1 """Tests for debugging machinery.
1 """Tests for debugging machinery.
2 """
2 """
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import bdb
7 import bdb
8 import builtins
8 import builtins
9 import os
9 import os
10 import sys
10 import sys
11 import platform
11 import platform
12
12
13 from tempfile import NamedTemporaryFile
13 from tempfile import NamedTemporaryFile
14 from textwrap import dedent
14 from textwrap import dedent
15 from unittest.mock import patch
15 from unittest.mock import patch
16
16
17 from IPython.core import debugger
17 from IPython.core import debugger
18 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
18 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
19 from IPython.testing.decorators import skip_win32
19 from IPython.testing.decorators import skip_win32
20 import pytest
20 import pytest
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Helper classes, from CPython's Pdb test suite
23 # Helper classes, from CPython's Pdb test suite
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 class _FakeInput(object):
26 class _FakeInput(object):
27 """
27 """
28 A fake input stream for pdb's interactive debugger. Whenever a
28 A fake input stream for pdb's interactive debugger. Whenever a
29 line is read, print it (to simulate the user typing it), and then
29 line is read, print it (to simulate the user typing it), and then
30 return it. The set of lines to return is specified in the
30 return it. The set of lines to return is specified in the
31 constructor; they should not have trailing newlines.
31 constructor; they should not have trailing newlines.
32 """
32 """
33 def __init__(self, lines):
33 def __init__(self, lines):
34 self.lines = iter(lines)
34 self.lines = iter(lines)
35
35
36 def readline(self):
36 def readline(self):
37 line = next(self.lines)
37 line = next(self.lines)
38 print(line)
38 print(line)
39 return line+'\n'
39 return line+'\n'
40
40
41 class PdbTestInput(object):
41 class PdbTestInput(object):
42 """Context manager that makes testing Pdb in doctests easier."""
42 """Context manager that makes testing Pdb in doctests easier."""
43
43
44 def __init__(self, input):
44 def __init__(self, input):
45 self.input = input
45 self.input = input
46
46
47 def __enter__(self):
47 def __enter__(self):
48 self.real_stdin = sys.stdin
48 self.real_stdin = sys.stdin
49 sys.stdin = _FakeInput(self.input)
49 sys.stdin = _FakeInput(self.input)
50
50
51 def __exit__(self, *exc):
51 def __exit__(self, *exc):
52 sys.stdin = self.real_stdin
52 sys.stdin = self.real_stdin
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Tests
55 # Tests
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58 def test_ipdb_magics():
58 def test_ipdb_magics():
59 '''Test calling some IPython magics from ipdb.
59 '''Test calling some IPython magics from ipdb.
60
60
61 First, set up some test functions and classes which we can inspect.
61 First, set up some test functions and classes which we can inspect.
62
62
63 >>> class ExampleClass(object):
63 >>> class ExampleClass(object):
64 ... """Docstring for ExampleClass."""
64 ... """Docstring for ExampleClass."""
65 ... def __init__(self):
65 ... def __init__(self):
66 ... """Docstring for ExampleClass.__init__"""
66 ... """Docstring for ExampleClass.__init__"""
67 ... pass
67 ... pass
68 ... def __str__(self):
68 ... def __str__(self):
69 ... return "ExampleClass()"
69 ... return "ExampleClass()"
70
70
71 >>> def example_function(x, y, z="hello"):
71 >>> def example_function(x, y, z="hello"):
72 ... """Docstring for example_function."""
72 ... """Docstring for example_function."""
73 ... pass
73 ... pass
74
74
75 >>> old_trace = sys.gettrace()
75 >>> old_trace = sys.gettrace()
76
76
77 Create a function which triggers ipdb.
77 Create a function which triggers ipdb.
78
78
79 >>> def trigger_ipdb():
79 >>> def trigger_ipdb():
80 ... a = ExampleClass()
80 ... a = ExampleClass()
81 ... debugger.Pdb().set_trace()
81 ... debugger.Pdb().set_trace()
82
82
83 >>> with PdbTestInput([
83 >>> with PdbTestInput([
84 ... 'pdef example_function',
84 ... 'pdef example_function',
85 ... 'pdoc ExampleClass',
85 ... 'pdoc ExampleClass',
86 ... 'up',
86 ... 'up',
87 ... 'down',
87 ... 'down',
88 ... 'list',
88 ... 'list',
89 ... 'pinfo a',
89 ... 'pinfo a',
90 ... 'll',
90 ... 'll',
91 ... 'continue',
91 ... 'continue',
92 ... ]):
92 ... ]):
93 ... trigger_ipdb()
93 ... trigger_ipdb()
94 --Return--
94 --Return--
95 None
95 None
96 > <doctest ...>(3)trigger_ipdb()
96 > <doctest ...>(3)trigger_ipdb()
97 1 def trigger_ipdb():
97 1 def trigger_ipdb():
98 2 a = ExampleClass()
98 2 a = ExampleClass()
99 ----> 3 debugger.Pdb().set_trace()
99 ----> 3 debugger.Pdb().set_trace()
100 <BLANKLINE>
100 <BLANKLINE>
101 ipdb> pdef example_function
101 ipdb> pdef example_function
102 example_function(x, y, z='hello')
102 example_function(x, y, z='hello')
103 ipdb> pdoc ExampleClass
103 ipdb> pdoc ExampleClass
104 Class docstring:
104 Class docstring:
105 Docstring for ExampleClass.
105 Docstring for ExampleClass.
106 Init docstring:
106 Init docstring:
107 Docstring for ExampleClass.__init__
107 Docstring for ExampleClass.__init__
108 ipdb> up
108 ipdb> up
109 > <doctest ...>(11)<module>()
109 > <doctest ...>(11)<module>()
110 7 'pinfo a',
110 7 'pinfo a',
111 8 'll',
111 8 'll',
112 9 'continue',
112 9 'continue',
113 10 ]):
113 10 ]):
114 ---> 11 trigger_ipdb()
114 ---> 11 trigger_ipdb()
115 <BLANKLINE>
115 <BLANKLINE>
116 ipdb> down
116 ipdb> down
117 None
117 None
118 > <doctest ...>(3)trigger_ipdb()
118 > <doctest ...>(3)trigger_ipdb()
119 1 def trigger_ipdb():
119 1 def trigger_ipdb():
120 2 a = ExampleClass()
120 2 a = ExampleClass()
121 ----> 3 debugger.Pdb().set_trace()
121 ----> 3 debugger.Pdb().set_trace()
122 <BLANKLINE>
122 <BLANKLINE>
123 ipdb> list
123 ipdb> list
124 1 def trigger_ipdb():
124 1 def trigger_ipdb():
125 2 a = ExampleClass()
125 2 a = ExampleClass()
126 ----> 3 debugger.Pdb().set_trace()
126 ----> 3 debugger.Pdb().set_trace()
127 <BLANKLINE>
127 <BLANKLINE>
128 ipdb> pinfo a
128 ipdb> pinfo a
129 Type: ExampleClass
129 Type: ExampleClass
130 String form: ExampleClass()
130 String form: ExampleClass()
131 Namespace: Local...
131 Namespace: Local...
132 Docstring: Docstring for ExampleClass.
132 Docstring: Docstring for ExampleClass.
133 Init docstring: Docstring for ExampleClass.__init__
133 Init docstring: Docstring for ExampleClass.__init__
134 ipdb> ll
134 ipdb> ll
135 1 def trigger_ipdb():
135 1 def trigger_ipdb():
136 2 a = ExampleClass()
136 2 a = ExampleClass()
137 ----> 3 debugger.Pdb().set_trace()
137 ----> 3 debugger.Pdb().set_trace()
138 <BLANKLINE>
138 <BLANKLINE>
139 ipdb> continue
139 ipdb> continue
140
140
141 Restore previous trace function, e.g. for coverage.py
141 Restore previous trace function, e.g. for coverage.py
142
142
143 >>> sys.settrace(old_trace)
143 >>> sys.settrace(old_trace)
144 '''
144 '''
145
145
146 def test_ipdb_magics2():
146 def test_ipdb_magics2():
147 '''Test ipdb with a very short function.
147 '''Test ipdb with a very short function.
148
148
149 >>> old_trace = sys.gettrace()
149 >>> old_trace = sys.gettrace()
150
150
151 >>> def bar():
151 >>> def bar():
152 ... pass
152 ... pass
153
153
154 Run ipdb.
154 Run ipdb.
155
155
156 >>> with PdbTestInput([
156 >>> with PdbTestInput([
157 ... 'continue',
157 ... 'continue',
158 ... ]):
158 ... ]):
159 ... debugger.Pdb().runcall(bar)
159 ... debugger.Pdb().runcall(bar)
160 > <doctest ...>(2)bar()
160 > <doctest ...>(2)bar()
161 1 def bar():
161 1 def bar():
162 ----> 2 pass
162 ----> 2 pass
163 <BLANKLINE>
163 <BLANKLINE>
164 ipdb> continue
164 ipdb> continue
165
165
166 Restore previous trace function, e.g. for coverage.py
166 Restore previous trace function, e.g. for coverage.py
167
167
168 >>> sys.settrace(old_trace)
168 >>> sys.settrace(old_trace)
169 '''
169 '''
170
170
171 def can_quit():
171 def can_quit():
172 '''Test that quit work in ipydb
172 '''Test that quit work in ipydb
173
173
174 >>> old_trace = sys.gettrace()
174 >>> old_trace = sys.gettrace()
175
175
176 >>> def bar():
176 >>> def bar():
177 ... pass
177 ... pass
178
178
179 >>> with PdbTestInput([
179 >>> with PdbTestInput([
180 ... 'quit',
180 ... 'quit',
181 ... ]):
181 ... ]):
182 ... debugger.Pdb().runcall(bar)
182 ... debugger.Pdb().runcall(bar)
183 > <doctest ...>(2)bar()
183 > <doctest ...>(2)bar()
184 1 def bar():
184 1 def bar():
185 ----> 2 pass
185 ----> 2 pass
186 <BLANKLINE>
186 <BLANKLINE>
187 ipdb> quit
187 ipdb> quit
188
188
189 Restore previous trace function, e.g. for coverage.py
189 Restore previous trace function, e.g. for coverage.py
190
190
191 >>> sys.settrace(old_trace)
191 >>> sys.settrace(old_trace)
192 '''
192 '''
193
193
194
194
195 def can_exit():
195 def can_exit():
196 '''Test that quit work in ipydb
196 '''Test that quit work in ipydb
197
197
198 >>> old_trace = sys.gettrace()
198 >>> old_trace = sys.gettrace()
199
199
200 >>> def bar():
200 >>> def bar():
201 ... pass
201 ... pass
202
202
203 >>> with PdbTestInput([
203 >>> with PdbTestInput([
204 ... 'exit',
204 ... 'exit',
205 ... ]):
205 ... ]):
206 ... debugger.Pdb().runcall(bar)
206 ... debugger.Pdb().runcall(bar)
207 > <doctest ...>(2)bar()
207 > <doctest ...>(2)bar()
208 1 def bar():
208 1 def bar():
209 ----> 2 pass
209 ----> 2 pass
210 <BLANKLINE>
210 <BLANKLINE>
211 ipdb> exit
211 ipdb> exit
212
212
213 Restore previous trace function, e.g. for coverage.py
213 Restore previous trace function, e.g. for coverage.py
214
214
215 >>> sys.settrace(old_trace)
215 >>> sys.settrace(old_trace)
216 '''
216 '''
217
217
218
218
219 def test_interruptible_core_debugger():
219 def test_interruptible_core_debugger():
220 """The debugger can be interrupted.
220 """The debugger can be interrupted.
221
221
222 The presumption is there is some mechanism that causes a KeyboardInterrupt
222 The presumption is there is some mechanism that causes a KeyboardInterrupt
223 (this is implemented in ipykernel). We want to ensure the
223 (this is implemented in ipykernel). We want to ensure the
224 KeyboardInterrupt cause debugging to cease.
224 KeyboardInterrupt cause debugging to cease.
225 """
225 """
226 def raising_input(msg="", called=[0]):
226 def raising_input(msg="", called=[0]):
227 called[0] += 1
227 called[0] += 1
228 assert called[0] == 1, "input() should only be called once!"
228 assert called[0] == 1, "input() should only be called once!"
229 raise KeyboardInterrupt()
229 raise KeyboardInterrupt()
230
230
231 tracer_orig = sys.gettrace()
231 tracer_orig = sys.gettrace()
232 try:
232 try:
233 with patch.object(builtins, "input", raising_input):
233 with patch.object(builtins, "input", raising_input):
234 debugger.InterruptiblePdb().set_trace()
234 debugger.InterruptiblePdb().set_trace()
235 # The way this test will fail is by set_trace() never exiting,
235 # The way this test will fail is by set_trace() never exiting,
236 # resulting in a timeout by the test runner. The alternative
236 # resulting in a timeout by the test runner. The alternative
237 # implementation would involve a subprocess, but that adds issues
237 # implementation would involve a subprocess, but that adds issues
238 # with interrupting subprocesses that are rather complex, so it's
238 # with interrupting subprocesses that are rather complex, so it's
239 # simpler just to do it this way.
239 # simpler just to do it this way.
240 finally:
240 finally:
241 # restore the original trace function
241 # restore the original trace function
242 sys.settrace(tracer_orig)
242 sys.settrace(tracer_orig)
243
243
244
244
245 @skip_win32
245 @skip_win32
246 def test_xmode_skip():
246 def test_xmode_skip():
247 """that xmode skip frames
247 """that xmode skip frames
248
248
249 Not as a doctest as pytest does not run doctests.
249 Not as a doctest as pytest does not run doctests.
250 """
250 """
251 import pexpect
251 import pexpect
252 env = os.environ.copy()
252 env = os.environ.copy()
253 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
253 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
254
254
255 child = pexpect.spawn(
255 child = pexpect.spawn(
256 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
256 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
257 )
257 )
258 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
258 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
259
259
260 child.expect("IPython")
260 child.expect("IPython")
261 child.expect("\n")
261 child.expect("\n")
262 child.expect_exact("In [1]")
262 child.expect_exact("In [1]")
263
263
264 block = dedent(
264 block = dedent(
265 """
265 """
266 def f():
266 def f():
267 __tracebackhide__ = True
267 __tracebackhide__ = True
268 g()
268 g()
269
269
270 def g():
270 def g():
271 raise ValueError
271 raise ValueError
272
272
273 f()
273 f()
274 """
274 """
275 )
275 )
276
276
277 for line in block.splitlines():
277 for line in block.splitlines():
278 child.sendline(line)
278 child.sendline(line)
279 child.expect_exact(line)
279 child.expect_exact(line)
280 child.expect_exact("skipping")
280 child.expect_exact("skipping")
281
281
282 block = dedent(
282 block = dedent(
283 """
283 """
284 def f():
284 def f():
285 __tracebackhide__ = True
285 __tracebackhide__ = True
286 g()
286 g()
287
287
288 def g():
288 def g():
289 from IPython.core.debugger import set_trace
289 from IPython.core.debugger import set_trace
290 set_trace()
290 set_trace()
291
291
292 f()
292 f()
293 """
293 """
294 )
294 )
295
295
296 for line in block.splitlines():
296 for line in block.splitlines():
297 child.sendline(line)
297 child.sendline(line)
298 child.expect_exact(line)
298 child.expect_exact(line)
299
299
300 child.expect("ipdb>")
300 child.expect("ipdb>")
301 child.sendline("w")
301 child.sendline("w")
302 child.expect("hidden")
302 child.expect("hidden")
303 child.expect("ipdb>")
303 child.expect("ipdb>")
304 child.sendline("skip_hidden false")
304 child.sendline("skip_hidden false")
305 child.sendline("w")
305 child.sendline("w")
306 child.expect("__traceba")
306 child.expect("__traceba")
307 child.expect("ipdb>")
307 child.expect("ipdb>")
308
308
309 child.close()
309 child.close()
310
310
311
311
312 skip_decorators_blocks = (
312 skip_decorators_blocks = (
313 """
313 """
314 def helpers_helper():
314 def helpers_helper():
315 pass # should not stop here except breakpoint
315 pass # should not stop here except breakpoint
316 """,
316 """,
317 """
317 """
318 def helper_1():
318 def helper_1():
319 helpers_helper() # should not stop here
319 helpers_helper() # should not stop here
320 """,
320 """,
321 """
321 """
322 def helper_2():
322 def helper_2():
323 pass # should not stop here
323 pass # should not stop here
324 """,
324 """,
325 """
325 """
326 def pdb_skipped_decorator2(function):
326 def pdb_skipped_decorator2(function):
327 def wrapped_fn(*args, **kwargs):
327 def wrapped_fn(*args, **kwargs):
328 __debuggerskip__ = True
328 __debuggerskip__ = True
329 helper_2()
329 helper_2()
330 __debuggerskip__ = False
330 __debuggerskip__ = False
331 result = function(*args, **kwargs)
331 result = function(*args, **kwargs)
332 __debuggerskip__ = True
332 __debuggerskip__ = True
333 helper_2()
333 helper_2()
334 return result
334 return result
335 return wrapped_fn
335 return wrapped_fn
336 """,
336 """,
337 """
337 """
338 def pdb_skipped_decorator(function):
338 def pdb_skipped_decorator(function):
339 def wrapped_fn(*args, **kwargs):
339 def wrapped_fn(*args, **kwargs):
340 __debuggerskip__ = True
340 __debuggerskip__ = True
341 helper_1()
341 helper_1()
342 __debuggerskip__ = False
342 __debuggerskip__ = False
343 result = function(*args, **kwargs)
343 result = function(*args, **kwargs)
344 __debuggerskip__ = True
344 __debuggerskip__ = True
345 helper_2()
345 helper_2()
346 return result
346 return result
347 return wrapped_fn
347 return wrapped_fn
348 """,
348 """,
349 """
349 """
350 @pdb_skipped_decorator
350 @pdb_skipped_decorator
351 @pdb_skipped_decorator2
351 @pdb_skipped_decorator2
352 def bar(x, y):
352 def bar(x, y):
353 return x * y
353 return x * y
354 """,
354 """,
355 """import IPython.terminal.debugger as ipdb""",
355 """import IPython.terminal.debugger as ipdb""",
356 """
356 """
357 def f():
357 def f():
358 ipdb.set_trace()
358 ipdb.set_trace()
359 bar(3, 4)
359 bar(3, 4)
360 """,
360 """,
361 """
361 """
362 f()
362 f()
363 """,
363 """,
364 )
364 )
365
365
366
366
367 def _decorator_skip_setup():
367 def _decorator_skip_setup():
368 import pexpect
368 import pexpect
369
369
370 env = os.environ.copy()
370 env = os.environ.copy()
371 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
371 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
372 env["PROMPT_TOOLKIT_NO_CPR"] = "1"
372
373
373 child = pexpect.spawn(
374 child = pexpect.spawn(
374 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
375 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
375 )
376 )
376 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
377 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
377
378
378 child.expect("IPython")
379 child.expect("IPython")
379 child.expect("\n")
380 child.expect("\n")
380
381
381 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
382 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
383 child.str_last_chars = 500
382
384
383 dedented_blocks = [dedent(b).strip() for b in skip_decorators_blocks]
385 dedented_blocks = [dedent(b).strip() for b in skip_decorators_blocks]
384 in_prompt_number = 1
386 in_prompt_number = 1
385 for cblock in dedented_blocks:
387 for cblock in dedented_blocks:
386 child.expect_exact(f"In [{in_prompt_number}]:")
388 child.expect_exact(f"In [{in_prompt_number}]:")
387 in_prompt_number += 1
389 in_prompt_number += 1
388 for line in cblock.splitlines():
390 for line in cblock.splitlines():
389 child.sendline(line)
391 child.sendline(line)
390 child.expect_exact(line)
392 child.expect_exact(line)
391 child.sendline("")
393 child.sendline("")
392 return child
394 return child
393
395
394
396
397 @pytest.mark.skip(reason="recently fail for unknown reason on CI")
395 @skip_win32
398 @skip_win32
396 def test_decorator_skip():
399 def test_decorator_skip():
397 """test that decorator frames can be skipped."""
400 """test that decorator frames can be skipped."""
398
401
399 child = _decorator_skip_setup()
402 child = _decorator_skip_setup()
400
403
404 child.expect_exact("ipython-input-8")
401 child.expect_exact("3 bar(3, 4)")
405 child.expect_exact("3 bar(3, 4)")
402 child.expect("ipdb>")
406 child.expect("ipdb>")
403
407
404 child.expect("ipdb>")
408 child.expect("ipdb>")
405 child.sendline("step")
409 child.sendline("step")
406 child.expect_exact("step")
410 child.expect_exact("step")
411 child.expect_exact("--Call--")
412 child.expect_exact("ipython-input-6")
407
413
408 child.expect_exact("1 @pdb_skipped_decorator")
414 child.expect_exact("1 @pdb_skipped_decorator")
409
415
410 child.sendline("s")
416 child.sendline("s")
411 child.expect_exact("return x * y")
417 child.expect_exact("return x * y")
412
418
413 child.close()
419 child.close()
414
420
415
421
422 @pytest.mark.skip(reason="recently fail for unknown reason on CI")
416 @pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy")
423 @pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy")
417 @skip_win32
424 @skip_win32
418 def test_decorator_skip_disabled():
425 def test_decorator_skip_disabled():
419 """test that decorator frame skipping can be disabled"""
426 """test that decorator frame skipping can be disabled"""
420
427
421 child = _decorator_skip_setup()
428 child = _decorator_skip_setup()
422
429
423 child.expect_exact("3 bar(3, 4)")
430 child.expect_exact("3 bar(3, 4)")
424
431
425 for input_, expected in [
432 for input_, expected in [
426 ("skip_predicates debuggerskip False", ""),
433 ("skip_predicates debuggerskip False", ""),
427 ("skip_predicates", "debuggerskip : False"),
434 ("skip_predicates", "debuggerskip : False"),
428 ("step", "---> 2 def wrapped_fn"),
435 ("step", "---> 2 def wrapped_fn"),
429 ("step", "----> 3 __debuggerskip__"),
436 ("step", "----> 3 __debuggerskip__"),
430 ("step", "----> 4 helper_1()"),
437 ("step", "----> 4 helper_1()"),
431 ("step", "---> 1 def helper_1():"),
438 ("step", "---> 1 def helper_1():"),
432 ("next", "----> 2 helpers_helper()"),
439 ("next", "----> 2 helpers_helper()"),
433 ("next", "--Return--"),
440 ("next", "--Return--"),
434 ("next", "----> 5 __debuggerskip__ = False"),
441 ("next", "----> 5 __debuggerskip__ = False"),
435 ]:
442 ]:
436 child.expect("ipdb>")
443 child.expect("ipdb>")
437 child.sendline(input_)
444 child.sendline(input_)
438 child.expect_exact(input_)
445 child.expect_exact(input_)
439 child.expect_exact(expected)
446 child.expect_exact(expected)
440
447
441 child.close()
448 child.close()
442
449
443
450
444 @pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy")
451 @pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy")
445 @skip_win32
452 @skip_win32
446 def test_decorator_skip_with_breakpoint():
453 def test_decorator_skip_with_breakpoint():
447 """test that decorator frame skipping can be disabled"""
454 """test that decorator frame skipping can be disabled"""
448
455
449 import pexpect
456 import pexpect
450
457
451 env = os.environ.copy()
458 env = os.environ.copy()
452 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
459 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
460 env["PROMPT_TOOLKIT_NO_CPR"] = "1"
453
461
454 child = pexpect.spawn(
462 child = pexpect.spawn(
455 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
463 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
456 )
464 )
457 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
465 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
466 child.str_last_chars = 500
458
467
459 child.expect("IPython")
468 child.expect("IPython")
460 child.expect("\n")
469 child.expect("\n")
461
470
462 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
471 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
463
472
464 ### we need a filename, so we need to exec the full block with a filename
473 ### we need a filename, so we need to exec the full block with a filename
465 with NamedTemporaryFile(suffix=".py", dir=".", delete=True) as tf:
474 with NamedTemporaryFile(suffix=".py", dir=".", delete=True) as tf:
466
475
467 name = tf.name[:-3].split("/")[-1]
476 name = tf.name[:-3].split("/")[-1]
468 tf.write("\n".join([dedent(x) for x in skip_decorators_blocks[:-1]]).encode())
477 tf.write("\n".join([dedent(x) for x in skip_decorators_blocks[:-1]]).encode())
469 tf.flush()
478 tf.flush()
470 codeblock = f"from {name} import f"
479 codeblock = f"from {name} import f"
471
480
472 dedented_blocks = [
481 dedented_blocks = [
473 codeblock,
482 codeblock,
474 "f()",
483 "f()",
475 ]
484 ]
476
485
477 in_prompt_number = 1
486 in_prompt_number = 1
478 for cblock in dedented_blocks:
487 for cblock in dedented_blocks:
479 child.expect_exact(f"In [{in_prompt_number}]:")
488 child.expect_exact(f"In [{in_prompt_number}]:")
480 in_prompt_number += 1
489 in_prompt_number += 1
481 for line in cblock.splitlines():
490 for line in cblock.splitlines():
482 child.sendline(line)
491 child.sendline(line)
483 child.expect_exact(line)
492 child.expect_exact(line)
484 child.sendline("")
493 child.sendline("")
485
494
486 # as the filename does not exists, we'll rely on the filename prompt
495 # as the filename does not exists, we'll rely on the filename prompt
487 child.expect_exact("47 bar(3, 4)")
496 child.expect_exact("47 bar(3, 4)")
488
497
489 for input_, expected in [
498 for input_, expected in [
490 (f"b {name}.py:3", ""),
499 (f"b {name}.py:3", ""),
491 ("step", "1---> 3 pass # should not stop here except"),
500 ("step", "1---> 3 pass # should not stop here except"),
492 ("step", "---> 38 @pdb_skipped_decorator"),
501 ("step", "---> 38 @pdb_skipped_decorator"),
493 ("continue", ""),
502 ("continue", ""),
494 ]:
503 ]:
495 child.expect("ipdb>")
504 child.expect("ipdb>")
496 child.sendline(input_)
505 child.sendline(input_)
497 child.expect_exact(input_)
506 child.expect_exact(input_)
498 child.expect_exact(expected)
507 child.expect_exact(expected)
499
508
500 child.close()
509 child.close()
501
510
502
511
503 @skip_win32
512 @skip_win32
504 def test_where_erase_value():
513 def test_where_erase_value():
505 """Test that `where` does not access f_locals and erase values."""
514 """Test that `where` does not access f_locals and erase values."""
506 import pexpect
515 import pexpect
507
516
508 env = os.environ.copy()
517 env = os.environ.copy()
509 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
518 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
510
519
511 child = pexpect.spawn(
520 child = pexpect.spawn(
512 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
521 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
513 )
522 )
514 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
523 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
515
524
516 child.expect("IPython")
525 child.expect("IPython")
517 child.expect("\n")
526 child.expect("\n")
518 child.expect_exact("In [1]")
527 child.expect_exact("In [1]")
519
528
520 block = dedent(
529 block = dedent(
521 """
530 """
522 def simple_f():
531 def simple_f():
523 myvar = 1
532 myvar = 1
524 print(myvar)
533 print(myvar)
525 1/0
534 1/0
526 print(myvar)
535 print(myvar)
527 simple_f() """
536 simple_f() """
528 )
537 )
529
538
530 for line in block.splitlines():
539 for line in block.splitlines():
531 child.sendline(line)
540 child.sendline(line)
532 child.expect_exact(line)
541 child.expect_exact(line)
533 child.expect_exact("ZeroDivisionError")
542 child.expect_exact("ZeroDivisionError")
534 child.expect_exact("In [2]:")
543 child.expect_exact("In [2]:")
535
544
536 child.sendline("%debug")
545 child.sendline("%debug")
537
546
538 ##
547 ##
539 child.expect("ipdb>")
548 child.expect("ipdb>")
540
549
541 child.sendline("myvar")
550 child.sendline("myvar")
542 child.expect("1")
551 child.expect("1")
543
552
544 ##
553 ##
545 child.expect("ipdb>")
554 child.expect("ipdb>")
546
555
547 child.sendline("myvar = 2")
556 child.sendline("myvar = 2")
548
557
549 ##
558 ##
550 child.expect_exact("ipdb>")
559 child.expect_exact("ipdb>")
551
560
552 child.sendline("myvar")
561 child.sendline("myvar")
553
562
554 child.expect_exact("2")
563 child.expect_exact("2")
555
564
556 ##
565 ##
557 child.expect("ipdb>")
566 child.expect("ipdb>")
558 child.sendline("where")
567 child.sendline("where")
559
568
560 ##
569 ##
561 child.expect("ipdb>")
570 child.expect("ipdb>")
562 child.sendline("myvar")
571 child.sendline("myvar")
563
572
564 child.expect_exact("2")
573 child.expect_exact("2")
565 child.expect("ipdb>")
574 child.expect("ipdb>")
566
575
567 child.close()
576 child.close()
@@ -1,167 +1,178 b''
1 import asyncio
1 import asyncio
2 import os
2 import os
3 import sys
3 import sys
4
4
5 from IPython.core.debugger import Pdb
5 from IPython.core.debugger import Pdb
6 from IPython.core.completer import IPCompleter
6 from IPython.core.completer import IPCompleter
7 from .ptutils import IPythonPTCompleter
7 from .ptutils import IPythonPTCompleter
8 from .shortcuts import create_ipython_shortcuts
8 from .shortcuts import create_ipython_shortcuts
9 from . import embed
9 from . import embed
10
10
11 from pathlib import Path
11 from pathlib import Path
12 from pygments.token import Token
12 from pygments.token import Token
13 from prompt_toolkit.shortcuts.prompt import PromptSession
13 from prompt_toolkit.shortcuts.prompt import PromptSession
14 from prompt_toolkit.enums import EditingMode
14 from prompt_toolkit.enums import EditingMode
15 from prompt_toolkit.formatted_text import PygmentsTokens
15 from prompt_toolkit.formatted_text import PygmentsTokens
16 from prompt_toolkit.history import InMemoryHistory, FileHistory
16 from prompt_toolkit.history import InMemoryHistory, FileHistory
17 from concurrent.futures import ThreadPoolExecutor
17 from concurrent.futures import ThreadPoolExecutor
18
18
19 from prompt_toolkit import __version__ as ptk_version
19 from prompt_toolkit import __version__ as ptk_version
20 PTK3 = ptk_version.startswith('3.')
20 PTK3 = ptk_version.startswith('3.')
21
21
22
22
23 # we want to avoid ptk as much as possible when using subprocesses
24 # as it uses cursor positioning requests, deletes color ....
25 _use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ
26
27
23 class TerminalPdb(Pdb):
28 class TerminalPdb(Pdb):
24 """Standalone IPython debugger."""
29 """Standalone IPython debugger."""
25
30
26 def __init__(self, *args, pt_session_options=None, **kwargs):
31 def __init__(self, *args, pt_session_options=None, **kwargs):
27 Pdb.__init__(self, *args, **kwargs)
32 Pdb.__init__(self, *args, **kwargs)
28 self._ptcomp = None
33 self._ptcomp = None
29 self.pt_init(pt_session_options)
34 self.pt_init(pt_session_options)
30 self.thread_executor = ThreadPoolExecutor(1)
35 self.thread_executor = ThreadPoolExecutor(1)
31
36
32 def pt_init(self, pt_session_options=None):
37 def pt_init(self, pt_session_options=None):
33 """Initialize the prompt session and the prompt loop
38 """Initialize the prompt session and the prompt loop
34 and store them in self.pt_app and self.pt_loop.
39 and store them in self.pt_app and self.pt_loop.
35
40
36 Additional keyword arguments for the PromptSession class
41 Additional keyword arguments for the PromptSession class
37 can be specified in pt_session_options.
42 can be specified in pt_session_options.
38 """
43 """
39 if pt_session_options is None:
44 if pt_session_options is None:
40 pt_session_options = {}
45 pt_session_options = {}
41
46
42 def get_prompt_tokens():
47 def get_prompt_tokens():
43 return [(Token.Prompt, self.prompt)]
48 return [(Token.Prompt, self.prompt)]
44
49
45 if self._ptcomp is None:
50 if self._ptcomp is None:
46 compl = IPCompleter(
51 compl = IPCompleter(
47 shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
52 shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
48 )
53 )
49 # add a completer for all the do_ methods
54 # add a completer for all the do_ methods
50 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
55 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
51
56
52 def gen_comp(self, text):
57 def gen_comp(self, text):
53 return [m for m in methods_names if m.startswith(text)]
58 return [m for m in methods_names if m.startswith(text)]
54 import types
59 import types
55 newcomp = types.MethodType(gen_comp, compl)
60 newcomp = types.MethodType(gen_comp, compl)
56 compl.custom_matchers.insert(0, newcomp)
61 compl.custom_matchers.insert(0, newcomp)
57 # end add completer.
62 # end add completer.
58
63
59 self._ptcomp = IPythonPTCompleter(compl)
64 self._ptcomp = IPythonPTCompleter(compl)
60
65
61 # setup history only when we start pdb
66 # setup history only when we start pdb
62 if self.shell.debugger_history is None:
67 if self.shell.debugger_history is None:
63 if self.shell.debugger_history_file is not None:
68 if self.shell.debugger_history_file is not None:
64
69
65 p = Path(self.shell.debugger_history_file).expanduser()
70 p = Path(self.shell.debugger_history_file).expanduser()
66 if not p.exists():
71 if not p.exists():
67 p.touch()
72 p.touch()
68 self.debugger_history = FileHistory(os.path.expanduser(str(p)))
73 self.debugger_history = FileHistory(os.path.expanduser(str(p)))
69 else:
74 else:
70 self.debugger_history = InMemoryHistory()
75 self.debugger_history = InMemoryHistory()
71 else:
76 else:
72 self.debugger_history = self.shell.debugger_history
77 self.debugger_history = self.shell.debugger_history
73
78
74 options = dict(
79 options = dict(
75 message=(lambda: PygmentsTokens(get_prompt_tokens())),
80 message=(lambda: PygmentsTokens(get_prompt_tokens())),
76 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
81 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
77 key_bindings=create_ipython_shortcuts(self.shell),
82 key_bindings=create_ipython_shortcuts(self.shell),
78 history=self.debugger_history,
83 history=self.debugger_history,
79 completer=self._ptcomp,
84 completer=self._ptcomp,
80 enable_history_search=True,
85 enable_history_search=True,
81 mouse_support=self.shell.mouse_support,
86 mouse_support=self.shell.mouse_support,
82 complete_style=self.shell.pt_complete_style,
87 complete_style=self.shell.pt_complete_style,
83 style=getattr(self.shell, "style", None),
88 style=getattr(self.shell, "style", None),
84 color_depth=self.shell.color_depth,
89 color_depth=self.shell.color_depth,
85 )
90 )
86
91
87 if not PTK3:
92 if not PTK3:
88 options['inputhook'] = self.shell.inputhook
93 options['inputhook'] = self.shell.inputhook
89 options.update(pt_session_options)
94 options.update(pt_session_options)
90 self.pt_loop = asyncio.new_event_loop()
95 if not _use_simple_prompt:
91 self.pt_app = PromptSession(**options)
96 self.pt_loop = asyncio.new_event_loop()
97 self.pt_app = PromptSession(**options)
92
98
93 def cmdloop(self, intro=None):
99 def cmdloop(self, intro=None):
94 """Repeatedly issue a prompt, accept input, parse an initial prefix
100 """Repeatedly issue a prompt, accept input, parse an initial prefix
95 off the received input, and dispatch to action methods, passing them
101 off the received input, and dispatch to action methods, passing them
96 the remainder of the line as argument.
102 the remainder of the line as argument.
97
103
98 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
104 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
99 """
105 """
100 if not self.use_rawinput:
106 if not self.use_rawinput:
101 raise ValueError('Sorry ipdb does not support use_rawinput=False')
107 raise ValueError('Sorry ipdb does not support use_rawinput=False')
102
108
103 # In order to make sure that prompt, which uses asyncio doesn't
109 # In order to make sure that prompt, which uses asyncio doesn't
104 # interfere with applications in which it's used, we always run the
110 # interfere with applications in which it's used, we always run the
105 # prompt itself in a different thread (we can't start an event loop
111 # prompt itself in a different thread (we can't start an event loop
106 # within an event loop). This new thread won't have any event loop
112 # within an event loop). This new thread won't have any event loop
107 # running, and here we run our prompt-loop.
113 # running, and here we run our prompt-loop.
108 self.preloop()
114 self.preloop()
109
115
110 try:
116 try:
111 if intro is not None:
117 if intro is not None:
112 self.intro = intro
118 self.intro = intro
113 if self.intro:
119 if self.intro:
114 print(self.intro, file=self.stdout)
120 print(self.intro, file=self.stdout)
115 stop = None
121 stop = None
116 while not stop:
122 while not stop:
117 if self.cmdqueue:
123 if self.cmdqueue:
118 line = self.cmdqueue.pop(0)
124 line = self.cmdqueue.pop(0)
119 else:
125 else:
120 self._ptcomp.ipy_completer.namespace = self.curframe_locals
126 self._ptcomp.ipy_completer.namespace = self.curframe_locals
121 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
127 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
122
128
123 # Run the prompt in a different thread.
129 # Run the prompt in a different thread.
124 try:
130 if not _use_simple_prompt:
125 line = self.thread_executor.submit(self.pt_app.prompt).result()
131 try:
126 except EOFError:
132 line = self.thread_executor.submit(
127 line = "EOF"
133 self.pt_app.prompt
134 ).result()
135 except EOFError:
136 line = "EOF"
137 else:
138 line = input("ipdb> ")
128
139
129 line = self.precmd(line)
140 line = self.precmd(line)
130 stop = self.onecmd(line)
141 stop = self.onecmd(line)
131 stop = self.postcmd(stop, line)
142 stop = self.postcmd(stop, line)
132 self.postloop()
143 self.postloop()
133 except Exception:
144 except Exception:
134 raise
145 raise
135
146
136 def do_interact(self, arg):
147 def do_interact(self, arg):
137 ipshell = embed.InteractiveShellEmbed(
148 ipshell = embed.InteractiveShellEmbed(
138 config=self.shell.config,
149 config=self.shell.config,
139 banner1="*interactive*",
150 banner1="*interactive*",
140 exit_msg="*exiting interactive console...*",
151 exit_msg="*exiting interactive console...*",
141 )
152 )
142 global_ns = self.curframe.f_globals
153 global_ns = self.curframe.f_globals
143 ipshell(
154 ipshell(
144 module=sys.modules.get(global_ns["__name__"], None),
155 module=sys.modules.get(global_ns["__name__"], None),
145 local_ns=self.curframe_locals,
156 local_ns=self.curframe_locals,
146 )
157 )
147
158
148
159
149 def set_trace(frame=None):
160 def set_trace(frame=None):
150 """
161 """
151 Start debugging from `frame`.
162 Start debugging from `frame`.
152
163
153 If frame is not specified, debugging starts from caller's frame.
164 If frame is not specified, debugging starts from caller's frame.
154 """
165 """
155 TerminalPdb().set_trace(frame or sys._getframe().f_back)
166 TerminalPdb().set_trace(frame or sys._getframe().f_back)
156
167
157
168
158 if __name__ == '__main__':
169 if __name__ == '__main__':
159 import pdb
170 import pdb
160 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
171 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
161 # bdb.BdbQuit. When started through __main__ and an exception
172 # bdb.BdbQuit. When started through __main__ and an exception
162 # happened after hitting "c", this is needed in order to
173 # happened after hitting "c", this is needed in order to
163 # be able to quit the debugging session (see #9950).
174 # be able to quit the debugging session (see #9950).
164 old_trace_dispatch = pdb.Pdb.trace_dispatch
175 old_trace_dispatch = pdb.Pdb.trace_dispatch
165 pdb.Pdb = TerminalPdb # type: ignore
176 pdb.Pdb = TerminalPdb # type: ignore
166 pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
177 pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
167 pdb.main()
178 pdb.main()
@@ -1,214 +1,214 b''
1 .. _ipython_as_shell:
2
1
3 .. note::
2 .. note::
4
3
5 This page has been kept for historical reason. You most likely want to use
4 This page has been kept for historical reason. You most likely want to use
6 `Xonsh <https://xon.sh/>`__ instead of this.
5 `Xonsh <https://xon.sh/>`__ instead of this.
7
6
7 .. _ipython_as_shell:
8
8
9 =========================
9 =========================
10 IPython as a system shell
10 IPython as a system shell
11 =========================
11 =========================
12
12
13
13
14
14
15 Overview
15 Overview
16 ========
16 ========
17
17
18 It is possible to adapt IPython for system shell usage. In the past, IPython
18 It is possible to adapt IPython for system shell usage. In the past, IPython
19 shipped a special 'sh' profile for this purpose, but it had been quarantined
19 shipped a special 'sh' profile for this purpose, but it had been quarantined
20 since 0.11 release, and in 1.0 it was removed altogether. Nevertheless, much
20 since 0.11 release, and in 1.0 it was removed altogether. Nevertheless, much
21 of this section relies on machinery which does not require a custom profile.
21 of this section relies on machinery which does not require a custom profile.
22
22
23 You can set up your own 'sh' :ref:`profile <Profiles>` to be different from
23 You can set up your own 'sh' :ref:`profile <Profiles>` to be different from
24 the default profile such that:
24 the default profile such that:
25
25
26 * Prompt shows the current directory (see `Prompt customization`_)
26 * Prompt shows the current directory (see `Prompt customization`_)
27 * Make system commands directly available (in alias table) by running the
27 * Make system commands directly available (in alias table) by running the
28 ``%rehashx`` magic. If you install new programs along your PATH, you might
28 ``%rehashx`` magic. If you install new programs along your PATH, you might
29 want to run ``%rehashx`` to update the alias table
29 want to run ``%rehashx`` to update the alias table
30 * turn ``%autocall`` to full mode
30 * turn ``%autocall`` to full mode
31
31
32
32
33 Environment variables
33 Environment variables
34 =====================
34 =====================
35
35
36 Rather than manipulating os.environ directly, you may like to use the magic
36 Rather than manipulating os.environ directly, you may like to use the magic
37 `%env` command. With no arguments, this displays all environment variables
37 `%env` command. With no arguments, this displays all environment variables
38 and values. To get the value of a specific variable, use `%env var`. To set
38 and values. To get the value of a specific variable, use `%env var`. To set
39 the value of a specific variable, use `%env foo bar`, `%env foo=bar`. By
39 the value of a specific variable, use `%env foo bar`, `%env foo=bar`. By
40 default values are considered to be strings so quoting them is unnecessary.
40 default values are considered to be strings so quoting them is unnecessary.
41 However, Python variables are expanded as usual in the magic command, so
41 However, Python variables are expanded as usual in the magic command, so
42 `%env foo=$bar` means "set the environment variable foo to the value of the
42 `%env foo=$bar` means "set the environment variable foo to the value of the
43 Python variable `bar`".
43 Python variable `bar`".
44
44
45 Aliases
45 Aliases
46 =======
46 =======
47
47
48 Once you run ``%rehashx``, all of your $PATH has been loaded as IPython aliases,
48 Once you run ``%rehashx``, all of your $PATH has been loaded as IPython aliases,
49 so you should be able to type any normal system command and have it executed.
49 so you should be able to type any normal system command and have it executed.
50 See ``%alias?`` and ``%unalias?`` for details on the alias facilities. See also
50 See ``%alias?`` and ``%unalias?`` for details on the alias facilities. See also
51 ``%rehashx?`` for details on the mechanism used to load $PATH.
51 ``%rehashx?`` for details on the mechanism used to load $PATH.
52
52
53 .. warning::
53 .. warning::
54
54
55 See info at the top of the page. You most likely want to use
55 See info at the top of the page. You most likely want to use
56 `Xonsh <https://xon.sh/>`__ instead of this.
56 `Xonsh <https://xon.sh/>`__ instead of this.
57
57
58 Directory management
58 Directory management
59 ====================
59 ====================
60
60
61 Since each command passed by IPython to the underlying system is executed
61 Since each command passed by IPython to the underlying system is executed
62 in a subshell which exits immediately, you can NOT use !cd to navigate
62 in a subshell which exits immediately, you can NOT use !cd to navigate
63 the filesystem.
63 the filesystem.
64
64
65 IPython provides its own builtin ``%cd`` magic command to move in the
65 IPython provides its own builtin ``%cd`` magic command to move in the
66 filesystem (the % is not required with automagic on). It also maintains
66 filesystem (the % is not required with automagic on). It also maintains
67 a list of visited directories (use ``%dhist`` to see it) and allows direct
67 a list of visited directories (use ``%dhist`` to see it) and allows direct
68 switching to any of them. Type ``cd?`` for more details.
68 switching to any of them. Type ``cd?`` for more details.
69
69
70 ``%pushd``, ``%popd`` and ``%dirs`` are provided for directory stack handling.
70 ``%pushd``, ``%popd`` and ``%dirs`` are provided for directory stack handling.
71
71
72
72
73 Prompt customization
73 Prompt customization
74 ====================
74 ====================
75
75
76 See :ref:`custom_prompts`.
76 See :ref:`custom_prompts`.
77
77
78
78
79 .. _string_lists:
79 .. _string_lists:
80
80
81 String lists
81 String lists
82 ============
82 ============
83
83
84 String lists (IPython.utils.text.SList) are handy way to process output
84 String lists (IPython.utils.text.SList) are handy way to process output
85 from system commands. They are produced by ``var = !cmd`` syntax.
85 from system commands. They are produced by ``var = !cmd`` syntax.
86
86
87 First, we acquire the output of 'ls -l'::
87 First, we acquire the output of 'ls -l'::
88
88
89 [Q:doc/examples]|2> lines = !ls -l
89 [Q:doc/examples]|2> lines = !ls -l
90 ==
90 ==
91 ['total 23',
91 ['total 23',
92 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
92 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
93 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
93 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
94 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
94 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
95 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
95 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
96 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
96 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
97 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
97 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
98 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
98 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
99
99
100 Now, let's take a look at the contents of 'lines' (the first number is
100 Now, let's take a look at the contents of 'lines' (the first number is
101 the list element number)::
101 the list element number)::
102
102
103 [Q:doc/examples]|3> lines
103 [Q:doc/examples]|3> lines
104 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
104 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
105
105
106 0: total 23
106 0: total 23
107 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
107 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
108 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
108 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
109 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
109 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
110 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
110 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
111 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
111 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
112 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
112 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
113 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
113 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
114
114
115 Now, let's filter out the 'embed' lines::
115 Now, let's filter out the 'embed' lines::
116
116
117 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
117 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
118 [Q:doc/examples]|5> l2
118 [Q:doc/examples]|5> l2
119 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
119 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
120
120
121 0: total 23
121 0: total 23
122 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
122 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
123 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
123 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
124 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
124 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
125 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
125 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
126 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
126 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
127
127
128 Now, we want strings having just file names and permissions::
128 Now, we want strings having just file names and permissions::
129
129
130 [Q:doc/examples]|6> l2.fields(8,0)
130 [Q:doc/examples]|6> l2.fields(8,0)
131 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
131 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
132
132
133 0: total
133 0: total
134 1: example-demo.py -rw-rw-rw-
134 1: example-demo.py -rw-rw-rw-
135 2: example-gnuplot.py -rwxrwxrwx
135 2: example-gnuplot.py -rwxrwxrwx
136 3: extension.py -rwxrwxrwx
136 3: extension.py -rwxrwxrwx
137 4: seteditor.py -rwxrwxrwx
137 4: seteditor.py -rwxrwxrwx
138 5: seteditor.pyc -rwxrwxrwx
138 5: seteditor.pyc -rwxrwxrwx
139
139
140 Note how the line with 'total' does not raise IndexError.
140 Note how the line with 'total' does not raise IndexError.
141
141
142 If you want to split these (yielding lists), call fields() without
142 If you want to split these (yielding lists), call fields() without
143 arguments::
143 arguments::
144
144
145 [Q:doc/examples]|7> _.fields()
145 [Q:doc/examples]|7> _.fields()
146 <7>
146 <7>
147 [['total'],
147 [['total'],
148 ['example-demo.py', '-rw-rw-rw-'],
148 ['example-demo.py', '-rw-rw-rw-'],
149 ['example-gnuplot.py', '-rwxrwxrwx'],
149 ['example-gnuplot.py', '-rwxrwxrwx'],
150 ['extension.py', '-rwxrwxrwx'],
150 ['extension.py', '-rwxrwxrwx'],
151 ['seteditor.py', '-rwxrwxrwx'],
151 ['seteditor.py', '-rwxrwxrwx'],
152 ['seteditor.pyc', '-rwxrwxrwx']]
152 ['seteditor.pyc', '-rwxrwxrwx']]
153
153
154 If you want to pass these separated with spaces to a command (typical
154 If you want to pass these separated with spaces to a command (typical
155 for lists if files), use the .s property::
155 for lists if files), use the .s property::
156
156
157
157
158 [Q:doc/examples]|13> files = l2.fields(8).s
158 [Q:doc/examples]|13> files = l2.fields(8).s
159 [Q:doc/examples]|14> files
159 [Q:doc/examples]|14> files
160 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
160 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
161 [Q:doc/examples]|15> ls $files
161 [Q:doc/examples]|15> ls $files
162 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
162 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
163
163
164 SLists are inherited from normal Python lists, so every list method is
164 SLists are inherited from normal Python lists, so every list method is
165 available::
165 available::
166
166
167 [Q:doc/examples]|21> lines.append('hey')
167 [Q:doc/examples]|21> lines.append('hey')
168
168
169
169
170 Real world example: remove all files outside version control
170 Real world example: remove all files outside version control
171 ------------------------------------------------------------
171 ------------------------------------------------------------
172
172
173 First, capture output of "hg status"::
173 First, capture output of "hg status"::
174
174
175 [Q:/ipython]|28> out = !hg status
175 [Q:/ipython]|28> out = !hg status
176 ==
176 ==
177 ['M IPython\\extensions\\ipy_kitcfg.py',
177 ['M IPython\\extensions\\ipy_kitcfg.py',
178 'M IPython\\extensions\\ipy_rehashdir.py',
178 'M IPython\\extensions\\ipy_rehashdir.py',
179 ...
179 ...
180 '? build\\lib\\IPython\\Debugger.py',
180 '? build\\lib\\IPython\\Debugger.py',
181 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
181 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
182 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
182 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
183 ...
183 ...
184
184
185 (lines starting with ? are not under version control).
185 (lines starting with ? are not under version control).
186
186
187 ::
187 ::
188
188
189 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
189 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
190 [Q:/ipython]|36> junk
190 [Q:/ipython]|36> junk
191 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
191 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
192 ...
192 ...
193 10: build\bdist.win32\winexe\temp\_ctypes.py
193 10: build\bdist.win32\winexe\temp\_ctypes.py
194 11: build\bdist.win32\winexe\temp\_hashlib.py
194 11: build\bdist.win32\winexe\temp\_hashlib.py
195 12: build\bdist.win32\winexe\temp\_socket.py
195 12: build\bdist.win32\winexe\temp\_socket.py
196
196
197 Now we can just remove these files by doing 'rm $junk.s'.
197 Now we can just remove these files by doing 'rm $junk.s'.
198
198
199 The .n, .s, .p properties
199 The .n, .s, .p properties
200 -------------------------
200 -------------------------
201
201
202 Properties of `SList <https://ipython.readthedocs.io/en/stable/api/generated/IPython.utils.text.html?highlight=SList#IPython.utils.text.SList>`_ wrapper
202 Properties of `SList <https://ipython.readthedocs.io/en/stable/api/generated/IPython.utils.text.html?highlight=SList#IPython.utils.text.SList>`_ wrapper
203 provide a convenient ways to use contained text in different formats:
203 provide a convenient ways to use contained text in different formats:
204
204
205 * ``.n`` returns (original) string with lines separated by a newline
205 * ``.n`` returns (original) string with lines separated by a newline
206 * ``.s`` returns string with lines separated by single space (for
206 * ``.s`` returns string with lines separated by single space (for
207 convenient passing to system commands)
207 convenient passing to system commands)
208 * ``.p`` returns list of "path" objects from detected file names
208 * ``.p`` returns list of "path" objects from detected file names
209
209
210 .. error::
210 .. error::
211
211
212 You went too far scroll back up. You most likely want to use
212 You went too far scroll back up. You most likely want to use
213 `Xonsh <https://xon.sh/>`__ instead of this.
213 `Xonsh <https://xon.sh/>`__ instead of this.
214
214
@@ -1,1797 +1,1798 b''
1 ============
1 ============
2 7.x Series
2 7.x Series
3 ============
3 ============
4
4
5 .. _version 7.34:
5 .. _version 7.34:
6
6
7 IPython 7.34
7 IPython 7.34
8 ============
8 ============
9
9
10 This version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
10 This version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
11 exit :ghpull:`13668`
11 exit :ghpull:`13668`
12
12
13
13
14 .. _version 7.33:
14 .. _version 7.33:
15
15
16 IPython 7.33
16 IPython 7.33
17 ============
17 ============
18
18
19 - Allow IPython hooks to receive current cell ids when frontend support it. See
19 - Allow IPython hooks to receive current cell ids when frontend support it. See
20 :ghpull:`13600`
20 :ghpull:`13600`
21
21
22 - ``?`` does not trigger the insertion of a new cell anymore as most frontend
22 - ``?`` does not trigger the insertion of a new cell anymore as most frontend
23 allow proper multiline edition. :ghpull:`13625`
23 allow proper multiline edition. :ghpull:`13625`
24
24
25
25
26 .. _version 7.32:
26 .. _version 7.32:
27
27
28 IPython 7.32
28 IPython 7.32
29 ============
29 ============
30
30
31
31
32
32
33 Autoload magic lazily
33 Autoload magic lazily
34 ---------------------
34 ---------------------
35
35
36 The ability to configure magics to be lazily loaded has been added to IPython.
36 The ability to configure magics to be lazily loaded has been added to IPython.
37 See the ``ipython --help-all`` section on ``MagicsManager.lazy_magic``.
37 See the ``ipython --help-all`` section on ``MagicsManager.lazy_magic``.
38 One can now use::
38 One can now use::
39
39
40 c.MagicsManager.lazy_magics = {
40 c.MagicsManager.lazy_magics = {
41 "my_magic": "slow.to.import",
41 "my_magic": "slow.to.import",
42 "my_other_magic": "also.slow",
42 "my_other_magic": "also.slow",
43 }
43 }
44
44
45 And on first use of ``%my_magic``, or corresponding cell magic, or other line magic,
45 And on first use of ``%my_magic``, or corresponding cell magic, or other line magic,
46 the corresponding ``load_ext`` will be called just before trying to invoke the magic.
46 the corresponding ``load_ext`` will be called just before trying to invoke the magic.
47
47
48 Misc
48 Misc
49 ----
49 ----
50
50
51 - Update sphinxify for Docrepr 0.2.0 :ghpull:`13503`.
51 - Update sphinxify for Docrepr 0.2.0 :ghpull:`13503`.
52 - Set co_name for cells run line by line (to fix debugging with Python 3.10)
52 - Set co_name for cells run line by line (to fix debugging with Python 3.10)
53 :ghpull:`13535`
53 :ghpull:`13535`
54
54
55
55
56 Many thanks to all the contributors to this release. You can find all individual
56 Many thanks to all the contributors to this release. You can find all individual
57 contributions to this milestone `on github
57 contributions to this milestone `on github
58 <https://github.com/ipython/ipython/milestone/99>`__.
58 <https://github.com/ipython/ipython/milestone/99>`__.
59
59
60 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
60 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
61 work on IPython and related libraries.
61 work on IPython and related libraries.
62
62
63 .. _version 7.31:
63 .. _version 7.31:
64
64
65 IPython 7.31
65 IPython 7.31
66 ============
66 ============
67
67
68 IPython 7.31 brings a couple of backports and fixes from the 8.0 branches,
68 IPython 7.31 brings a couple of backports and fixes from the 8.0 branches,
69 it is likely one of the last releases of the 7.x series, as 8.0 will probably be released
69 it is likely one of the last releases of the 7.x series, as 8.0 will probably be released
70 between this release and what would have been 7.32.
70 between this release and what would have been 7.32.
71
71
72 Please test 8.0 beta/rc releases in addition to this release.
72 Please test 8.0 beta/rc releases in addition to this release.
73
73
74 This Releases:
74 This Releases:
75 - Backport some fixes for Python 3.10 (:ghpull:`13412`)
75 - Backport some fixes for Python 3.10 (:ghpull:`13412`)
76 - use full-alpha transparency on dvipng rendered LaTeX (:ghpull:`13372`)
76 - use full-alpha transparency on dvipng rendered LaTeX (:ghpull:`13372`)
77
77
78 Many thanks to all the contributors to this release. You can find all individual
78 Many thanks to all the contributors to this release. You can find all individual
79 contributions to this milestone `on github
79 contributions to this milestone `on github
80 <https://github.com/ipython/ipython/milestone/95>`__.
80 <https://github.com/ipython/ipython/milestone/95>`__.
81
81
82 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
82 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
83 work on IPython and related libraries.
83 work on IPython and related libraries.
84
84
85
85
86 .. _version 7.30:
86 .. _version 7.30:
87
87
88 IPython 7.30
88 IPython 7.30
89 ============
89 ============
90
90
91 IPython 7.30 fixes a couple of bugs introduce in previous releases (in
91 IPython 7.30 fixes a couple of bugs introduce in previous releases (in
92 particular with respect to path handling), and introduce a few features and
92 particular with respect to path handling), and introduce a few features and
93 improvements:
93 improvements:
94
94
95 Notably we will highlight :ghpull:`13267` "Document that ``%run`` can execute
95 Notably we will highlight :ghpull:`13267` "Document that ``%run`` can execute
96 notebooks and ipy scripts.", which is the first commit of Fernando PΓ©rez since
96 notebooks and ipy scripts.", which is the first commit of Fernando PΓ©rez since
97 mid 2016 (IPython 5.1). If you are new to IPython, Fernando created IPython in
97 mid 2016 (IPython 5.1). If you are new to IPython, Fernando created IPython in
98 2001. The other most recent contribution of Fernando to IPython itself was
98 2001. The other most recent contribution of Fernando to IPython itself was
99 May 2018, by reviewing and merging PRs. I want to note that Fernando is still
99 May 2018, by reviewing and merging PRs. I want to note that Fernando is still
100 active but mostly as a mentor and leader of the whole Jupyter organisation, but
100 active but mostly as a mentor and leader of the whole Jupyter organisation, but
101 we're still happy to see him contribute code !
101 we're still happy to see him contribute code !
102
102
103 :ghpull:`13290` "Use sphinxify (if available) in object_inspect_mime path"
103 :ghpull:`13290` "Use sphinxify (if available) in object_inspect_mime path"
104 should allow richer Repr of docstrings when using jupyterlab inspector.
104 should allow richer Repr of docstrings when using jupyterlab inspector.
105
105
106 :ghpull:`13311` make the debugger use ``ThreadPoolExecutor`` for debugger cmdloop.
106 :ghpull:`13311` make the debugger use ``ThreadPoolExecutor`` for debugger cmdloop.
107 This should fix some issues/infinite loop, but let us know if you come across
107 This should fix some issues/infinite loop, but let us know if you come across
108 any regressions. In particular this fixes issues with `kmaork/madbg <https://github.com/kmaork/madbg>`_,
108 any regressions. In particular this fixes issues with `kmaork/madbg <https://github.com/kmaork/madbg>`_,
109 a remote debugger for IPython.
109 a remote debugger for IPython.
110
110
111 Note that this is likely the ante-penultimate release of IPython 7.x as a stable
111 Note that this is likely the ante-penultimate release of IPython 7.x as a stable
112 branch, as I hope to release IPython 8.0 as well as IPython 7.31 next
112 branch, as I hope to release IPython 8.0 as well as IPython 7.31 next
113 month/early 2022.
113 month/early 2022.
114
114
115 IPython 8.0 will drop support for Python 3.7, removed nose as a dependency, and
115 IPython 8.0 will drop support for Python 3.7, removed nose as a dependency, and
116 7.x will only get critical bug fixes with 8.x becoming the new stable. This will
116 7.x will only get critical bug fixes with 8.x becoming the new stable. This will
117 not be possible without `NumFOCUS Small Development Grants
117 not be possible without `NumFOCUS Small Development Grants
118 <https://numfocus.org/programs/small-development-grants>`_ Which allowed us to
118 <https://numfocus.org/programs/small-development-grants>`_ Which allowed us to
119 hire `Nikita Kniazev <https://github.com/Kojoley>`_ who provide Python and C++
119 hire `Nikita Kniazev <https://github.com/Kojoley>`_ who provide Python and C++
120 help and contracting work.
120 help and contracting work.
121
121
122
122
123 Many thanks to all the contributors to this release. You can find all individual
123 Many thanks to all the contributors to this release. You can find all individual
124 contributions to this milestone `on github
124 contributions to this milestone `on github
125 <https://github.com/ipython/ipython/milestone/94?closed=1>`__.
125 <https://github.com/ipython/ipython/milestone/94?closed=1>`__.
126
126
127 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
127 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
128 work on IPython and related libraries.
128 work on IPython and related libraries.
129
129
130
130
131 .. _version 7.29:
131 .. _version 7.29:
132
132
133 IPython 7.29
133 IPython 7.29
134 ============
134 ============
135
135
136
136
137 IPython 7.29 brings a couple of new functionalities to IPython and a number of bugfixes.
137 IPython 7.29 brings a couple of new functionalities to IPython and a number of bugfixes.
138 It is one of the largest recent release, relatively speaking, with close to 15 Pull Requests.
138 It is one of the largest recent release, relatively speaking, with close to 15 Pull Requests.
139
139
140
140
141 - fix an issue where base64 was returned instead of bytes when showing figures :ghpull:`13162`
141 - fix an issue where base64 was returned instead of bytes when showing figures :ghpull:`13162`
142 - fix compatibility with PyQt6, PySide 6 :ghpull:`13172`. This may be of
142 - fix compatibility with PyQt6, PySide 6 :ghpull:`13172`. This may be of
143 interest if you are running on Apple Silicon as only qt6.2+ is natively
143 interest if you are running on Apple Silicon as only qt6.2+ is natively
144 compatible.
144 compatible.
145 - fix matplotlib qtagg eventloop :ghpull:`13179`
145 - fix matplotlib qtagg eventloop :ghpull:`13179`
146 - Multiple docs fixes, typos, ... etc.
146 - Multiple docs fixes, typos, ... etc.
147 - Debugger will now exit by default on SigInt :ghpull:`13218`, this will be
147 - Debugger will now exit by default on SigInt :ghpull:`13218`, this will be
148 useful in notebook/lab if you forgot to exit the debugger. "Interrupt Kernel"
148 useful in notebook/lab if you forgot to exit the debugger. "Interrupt Kernel"
149 will now exist the debugger.
149 will now exist the debugger.
150
150
151 It give Pdb the ability to skip code in decorators. If functions contain a
151 It give Pdb the ability to skip code in decorators. If functions contain a
152 special value names ``__debuggerskip__ = True|False``, the function will not be
152 special value names ``__debuggerskip__ = True|False``, the function will not be
153 stepped into, and Pdb will step into lower frames only if the value is set to
153 stepped into, and Pdb will step into lower frames only if the value is set to
154 ``False``. The exact behavior is still likely to have corner cases and will be
154 ``False``. The exact behavior is still likely to have corner cases and will be
155 refined in subsequent releases. Feedback welcome. See the debugger module
155 refined in subsequent releases. Feedback welcome. See the debugger module
156 documentation for more info. Thanks to the `D. E. Shaw
156 documentation for more info. Thanks to the `D. E. Shaw
157 group <https://deshaw.com/>`__ for funding this feature.
157 group <https://deshaw.com/>`__ for funding this feature.
158
158
159 The main branch of IPython is receiving a number of changes as we received a
159 The main branch of IPython is receiving a number of changes as we received a
160 `NumFOCUS SDG <https://numfocus.org/programs/small-development-grants>`__
160 `NumFOCUS SDG <https://numfocus.org/programs/small-development-grants>`__
161 ($4800), to help us finish replacing ``nose`` by ``pytest``, and make IPython
161 ($4800), to help us finish replacing ``nose`` by ``pytest``, and make IPython
162 future proof with an 8.0 release.
162 future proof with an 8.0 release.
163
163
164
164
165 Many thanks to all the contributors to this release. You can find all individual
165 Many thanks to all the contributors to this release. You can find all individual
166 contributions to this milestone `on github
166 contributions to this milestone `on github
167 <https://github.com/ipython/ipython/milestone/93>`__.
167 <https://github.com/ipython/ipython/milestone/93>`__.
168
168
169 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
169 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
170 work on IPython and related libraries.
170 work on IPython and related libraries.
171
171
172
172
173 .. _version 7.28:
173 .. _version 7.28:
174
174
175 IPython 7.28
175 IPython 7.28
176 ============
176 ============
177
177
178
178
179 IPython 7.28 is again a minor release that mostly bring bugfixes, and couple of
179 IPython 7.28 is again a minor release that mostly bring bugfixes, and couple of
180 improvement. Many thanks to MrMino, who again did all the work this month, and
180 improvement. Many thanks to MrMino, who again did all the work this month, and
181 made a number of documentation improvements.
181 made a number of documentation improvements.
182
182
183 Here is a non-exhaustive list of changes,
183 Here is a non-exhaustive list of changes,
184
184
185 Fixes:
185 Fixes:
186
186
187 - async with doesn't allow newlines :ghpull:`13090`
187 - async with doesn't allow newlines :ghpull:`13090`
188 - Dynamically changing to vi mode via %config magic) :ghpull:`13091`
188 - Dynamically changing to vi mode via %config magic) :ghpull:`13091`
189
189
190 Virtualenv handling fixes:
190 Virtualenv handling fixes:
191
191
192 - init_virtualenv now uses Pathlib :ghpull:`12548`
192 - init_virtualenv now uses Pathlib :ghpull:`12548`
193 - Fix Improper path comparison of virtualenv directories :ghpull:`13140`
193 - Fix Improper path comparison of virtualenv directories :ghpull:`13140`
194 - Fix virtual environment user warning for lower case pathes :ghpull:`13094`
194 - Fix virtual environment user warning for lower case pathes :ghpull:`13094`
195 - Adapt to all sorts of drive names for cygwin :ghpull:`13153`
195 - Adapt to all sorts of drive names for cygwin :ghpull:`13153`
196
196
197 New Features:
197 New Features:
198
198
199 - enable autoplay in embed YouTube player :ghpull:`13133`
199 - enable autoplay in embed YouTube player :ghpull:`13133`
200
200
201 Documentation:
201 Documentation:
202
202
203 - Fix formatting for the core.interactiveshell documentation :ghpull:`13118`
203 - Fix formatting for the core.interactiveshell documentation :ghpull:`13118`
204 - Fix broken ipyparallel's refs :ghpull:`13138`
204 - Fix broken ipyparallel's refs :ghpull:`13138`
205 - Improve formatting of %time documentation :ghpull:`13125`
205 - Improve formatting of %time documentation :ghpull:`13125`
206 - Reword the YouTubeVideo autoplay WN :ghpull:`13147`
206 - Reword the YouTubeVideo autoplay WN :ghpull:`13147`
207
207
208
208
209 Highlighted features
209 Highlighted features
210 --------------------
210 --------------------
211
211
212
212
213 ``YouTubeVideo`` autoplay and the ability to add extra attributes to ``IFrame``
213 ``YouTubeVideo`` autoplay and the ability to add extra attributes to ``IFrame``
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
215
215
216 You can add any extra attributes to the ``<iframe>`` tag using the new
216 You can add any extra attributes to the ``<iframe>`` tag using the new
217 ``extras`` argument in the ``IFrame`` class. For example::
217 ``extras`` argument in the ``IFrame`` class. For example::
218
218
219 In [1]: from IPython.display import IFrame
219 In [1]: from IPython.display import IFrame
220
220
221 In [2]: IFrame(src="src", width=300, height=300, extras=['loading="eager"'])
221 In [2]: IFrame(src="src", width=300, height=300, extras=['loading="eager"'])
222
222
223 The above cells will result in the following HTML code being displayed in a
223 The above cells will result in the following HTML code being displayed in a
224 notebook::
224 notebook::
225
225
226 <iframe
226 <iframe
227 width="300"
227 width="300"
228 height="300"
228 height="300"
229 src="src"
229 src="src"
230 frameborder="0"
230 frameborder="0"
231 allowfullscreen
231 allowfullscreen
232 loading="eager"
232 loading="eager"
233 ></iframe>
233 ></iframe>
234
234
235 Related to the above, the ``YouTubeVideo`` class now takes an
235 Related to the above, the ``YouTubeVideo`` class now takes an
236 ``allow_autoplay`` flag, which sets up the iframe of the embedded YouTube video
236 ``allow_autoplay`` flag, which sets up the iframe of the embedded YouTube video
237 such that it allows autoplay.
237 such that it allows autoplay.
238
238
239 .. note::
239 .. note::
240 Whether this works depends on the autoplay policy of the browser rendering
240 Whether this works depends on the autoplay policy of the browser rendering
241 the HTML allowing it. It also could get blocked by some browser extensions.
241 the HTML allowing it. It also could get blocked by some browser extensions.
242
242
243 Try it out!
243 Try it out!
244
244 ::
245 ::
245
246
246 In [1]: from IPython.display import YouTubeVideo
247 In [1]: from IPython.display import YouTubeVideo
247
248
248 In [2]: YouTubeVideo("dQw4w9WgXcQ", allow_autoplay=True)
249 In [2]: YouTubeVideo("dQw4w9WgXcQ", allow_autoplay=True)
249
250
250
251
251
252
252 Thanks
253 Thanks
253 ------
254 ------
254
255
255 Many thanks to all the contributors to this release. You can find all individual
256 Many thanks to all the contributors to this release. You can find all individual
256 contributions to this milestone `on github
257 contributions to this milestone `on github
257 <https://github.com/ipython/ipython/milestone/92>`__.
258 <https://github.com/ipython/ipython/milestone/92>`__.
258
259
259 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
260 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
260 work on IPython and related libraries.
261 work on IPython and related libraries.
261
262
262
263
263 .. _version 7.27:
264 .. _version 7.27:
264
265
265 IPython 7.27
266 IPython 7.27
266 ============
267 ============
267
268
268 IPython 7.27 is a minor release that fixes a couple of issues and compatibility.
269 IPython 7.27 is a minor release that fixes a couple of issues and compatibility.
269
270
270 - Add support for GTK4 :ghpull:`131011`
271 - Add support for GTK4 :ghpull:`131011`
271 - Add support for Qt6 :ghpull:`13085`
272 - Add support for Qt6 :ghpull:`13085`
272 - Fix an issue with pip magic on windows :ghpull:`13093`
273 - Fix an issue with pip magic on windows :ghpull:`13093`
273
274
274 Thanks
275 Thanks
275 ------
276 ------
276
277
277 Many thanks to all the contributors to this release. You can find all individual
278 Many thanks to all the contributors to this release. You can find all individual
278 contributions to this milestone `on github
279 contributions to this milestone `on github
279 <https://github.com/ipython/ipython/milestone/91>`__.
280 <https://github.com/ipython/ipython/milestone/91>`__.
280
281
281 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
282 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
282 work on IPython and related libraries.
283 work on IPython and related libraries.
283
284
284 .. _version 7.26:
285 .. _version 7.26:
285
286
286 IPython 7.26
287 IPython 7.26
287 ============
288 ============
288
289
289 IPython 7.26 is a minor release that fixes a couple of issues, updates in API
290 IPython 7.26 is a minor release that fixes a couple of issues, updates in API
290 and Copyright/Licenses issues around various part of the codebase.
291 and Copyright/Licenses issues around various part of the codebase.
291
292
292 We'll highlight `this issue <https://github.com/ipython/ipython/issues/13039>`
293 We'll highlight `this issue <https://github.com/ipython/ipython/issues/13039>`
293 pointing out we were including and refereeing to code from Stack Overflow which
294 pointing out we were including and refereeing to code from Stack Overflow which
294 was CC-BY-SA, hence incompatible with the BSD license of IPython. This lead us
295 was CC-BY-SA, hence incompatible with the BSD license of IPython. This lead us
295 to a rewriting of the corresponding logic which in our case was done in a more
296 to a rewriting of the corresponding logic which in our case was done in a more
296 efficient way (in our case we were searching string prefixes instead of full
297 efficient way (in our case we were searching string prefixes instead of full
297 strings).
298 strings).
298
299
299 You will notice also a number of documentation improvements and cleanup.
300 You will notice also a number of documentation improvements and cleanup.
300
301
301 Of particular interest are the following Pull-requests:
302 Of particular interest are the following Pull-requests:
302
303
303
304
304 - The IPython directive now uses Sphinx logging for warnings. :ghpull:`13030`.
305 - The IPython directive now uses Sphinx logging for warnings. :ghpull:`13030`.
305 - Add expiry days option to pastebin magic and change http protocol to https.
306 - Add expiry days option to pastebin magic and change http protocol to https.
306 :ghpull:`13056`
307 :ghpull:`13056`
307 - Make Ipython.utils.timing work with jupyterlite :ghpull:`13050`.
308 - Make Ipython.utils.timing work with jupyterlite :ghpull:`13050`.
308
309
309 Pastebin magic expiry days option
310 Pastebin magic expiry days option
310 ---------------------------------
311 ---------------------------------
311
312
312 The Pastebin magic now has ``-e`` option to determine
313 The Pastebin magic now has ``-e`` option to determine
313 the number of days for paste expiration. For example
314 the number of days for paste expiration. For example
314 the paste that created with ``%pastebin -e 20 1`` magic will
315 the paste that created with ``%pastebin -e 20 1`` magic will
315 be available for next 20 days.
316 be available for next 20 days.
316
317
317
318
318
319
319
320
320
321
321 Thanks
322 Thanks
322 ------
323 ------
323
324
324 Many thanks to all the contributors to this release and in particular MrMino who
325 Many thanks to all the contributors to this release and in particular MrMino who
325 is doing most of the work those days. You can find all individual contributions
326 is doing most of the work those days. You can find all individual contributions
326 to this milestone `on github <https://github.com/ipython/ipython/milestone/90>`__.
327 to this milestone `on github <https://github.com/ipython/ipython/milestone/90>`__.
327
328
328 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
329 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
329 work on IPython and related libraries.
330 work on IPython and related libraries.
330
331
331
332
332 .. _version 7.25:
333 .. _version 7.25:
333
334
334 IPython 7.25
335 IPython 7.25
335 ============
336 ============
336
337
337 IPython 7.25 is a minor release that contains a single bugfix, which is highly
338 IPython 7.25 is a minor release that contains a single bugfix, which is highly
338 recommended for all users of ipdb, ipython debugger %debug magic and similar.
339 recommended for all users of ipdb, ipython debugger %debug magic and similar.
339
340
340 Issuing commands like ``where`` from within the debugger would reset the
341 Issuing commands like ``where`` from within the debugger would reset the
341 local variables changes made by the user. It is interesting to look at the root
342 local variables changes made by the user. It is interesting to look at the root
342 cause of the issue as accessing an attribute (``frame.f_locals``) would trigger
343 cause of the issue as accessing an attribute (``frame.f_locals``) would trigger
343 this side effects.
344 this side effects.
344
345
345 Thanks in particular to the patience from the reporters at D.E. Shaw for their
346 Thanks in particular to the patience from the reporters at D.E. Shaw for their
346 initial bug report that was due to a similar coding oversight in an extension,
347 initial bug report that was due to a similar coding oversight in an extension,
347 and who took time to debug and narrow down the problem.
348 and who took time to debug and narrow down the problem.
348
349
349 Thanks
350 Thanks
350 ------
351 ------
351
352
352 Many thanks to all the contributors to this release you can find all individual
353 Many thanks to all the contributors to this release you can find all individual
353 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/89>`__.
354 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/89>`__.
354
355
355 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
356 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
356 work on IPython and related libraries.
357 work on IPython and related libraries.
357
358
358
359
359 .. _version 7.24:
360 .. _version 7.24:
360
361
361 IPython 7.24
362 IPython 7.24
362 ============
363 ============
363
364
364 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
365 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
365 typical updates:
366 typical updates:
366
367
367 Misc
368 Misc
368 ----
369 ----
369
370
370
371
371 - Fix an issue where ``%recall`` would both succeeded and print an error message
372 - Fix an issue where ``%recall`` would both succeeded and print an error message
372 it failed. :ghpull:`12952`
373 it failed. :ghpull:`12952`
373 - Drop support for NumPy 1.16 – practically has no effect beyond indicating in
374 - Drop support for NumPy 1.16 – practically has no effect beyond indicating in
374 package metadata that we do not support it. :ghpull:`12937`
375 package metadata that we do not support it. :ghpull:`12937`
375
376
376 Debugger improvements
377 Debugger improvements
377 ---------------------
378 ---------------------
378
379
379 The debugger (and ``%debug`` magic) have been improved and can skip or hide frames
380 The debugger (and ``%debug`` magic) have been improved and can skip or hide frames
380 originating from files that are not writable to the user, as these are less
381 originating from files that are not writable to the user, as these are less
381 likely to be the source of errors, or be part of system files this can be a useful
382 likely to be the source of errors, or be part of system files this can be a useful
382 addition when debugging long errors.
383 addition when debugging long errors.
383
384
384 In addition to the global ``skip_hidden True|False`` command, the debugger has
385 In addition to the global ``skip_hidden True|False`` command, the debugger has
385 gained finer grained control of predicates as to whether to a frame should be
386 gained finer grained control of predicates as to whether to a frame should be
386 considered hidden. So far 3 predicates are available :
387 considered hidden. So far 3 predicates are available :
387
388
388 - ``tbhide``: frames containing the local variable ``__tracebackhide__`` set to
389 - ``tbhide``: frames containing the local variable ``__tracebackhide__`` set to
389 True.
390 True.
390 - ``readonly``: frames originating from readonly files, set to False.
391 - ``readonly``: frames originating from readonly files, set to False.
391 - ``ipython_internal``: frames that are likely to be from IPython internal
392 - ``ipython_internal``: frames that are likely to be from IPython internal
392 code, set to True.
393 code, set to True.
393
394
394 You can toggle individual predicates during a session with
395 You can toggle individual predicates during a session with
395
396
396 .. code-block::
397 .. code-block::
397
398
398 ipdb> skip_predicates readonly True
399 ipdb> skip_predicates readonly True
399
400
400 Read-only files will now be considered hidden frames.
401 Read-only files will now be considered hidden frames.
401
402
402
403
403 You can call ``skip_predicates`` without arguments to see the states of current
404 You can call ``skip_predicates`` without arguments to see the states of current
404 predicates:
405 predicates:
405
406
406 .. code-block::
407 .. code-block::
407
408
408 ipdb> skip_predicates
409 ipdb> skip_predicates
409 current predicates:
410 current predicates:
410 tbhide : True
411 tbhide : True
411 readonly : False
412 readonly : False
412 ipython_internal : True
413 ipython_internal : True
413
414
414 If all predicates are set to ``False``, ``skip_hidden`` will practically have
415 If all predicates are set to ``False``, ``skip_hidden`` will practically have
415 no effect. We attempt to warn you when all predicates are False.
416 no effect. We attempt to warn you when all predicates are False.
416
417
417 Note that the ``readonly`` predicate may increase disk access as we check for
418 Note that the ``readonly`` predicate may increase disk access as we check for
418 file access permission for all frames on many command invocation, but is usually
419 file access permission for all frames on many command invocation, but is usually
419 cached by operating systems. Let us know if you encounter any issues.
420 cached by operating systems. Let us know if you encounter any issues.
420
421
421 As the IPython debugger does not use the traitlets infrastructure for
422 As the IPython debugger does not use the traitlets infrastructure for
422 configuration, by editing your ``.pdbrc`` files and appending commands you would
423 configuration, by editing your ``.pdbrc`` files and appending commands you would
423 like to be executed just before entering the interactive prompt. For example:
424 like to be executed just before entering the interactive prompt. For example:
424
425
425
426
426 .. code::
427 .. code::
427
428
428 # file : ~/.pdbrc
429 # file : ~/.pdbrc
429 skip_predicates readonly True
430 skip_predicates readonly True
430 skip_predicates tbhide False
431 skip_predicates tbhide False
431
432
432 Will hide read only frames by default and show frames marked with
433 Will hide read only frames by default and show frames marked with
433 ``__tracebackhide__``.
434 ``__tracebackhide__``.
434
435
435
436
436
437
437
438
438 Thanks
439 Thanks
439 ------
440 ------
440
441
441 Many thanks to all the contributors to this release you can find all individual
442 Many thanks to all the contributors to this release you can find all individual
442 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/87>`__.
443 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/87>`__.
443
444
444 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
445 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
445 work on IPython and related libraries, in particular above mentioned
446 work on IPython and related libraries, in particular above mentioned
446 improvements to the debugger.
447 improvements to the debugger.
447
448
448
449
449
450
450
451
451 .. _version 7.23:
452 .. _version 7.23:
452
453
453 IPython 7.23 and 7.23.1
454 IPython 7.23 and 7.23.1
454 =======================
455 =======================
455
456
456
457
457 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
458 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
458 typical updates:
459 typical updates:
459
460
460 - We moved to GitHub actions away from Travis-CI, the transition may not be
461 - We moved to GitHub actions away from Travis-CI, the transition may not be
461 100% complete (not testing on nightly anymore), but as we ran out of
462 100% complete (not testing on nightly anymore), but as we ran out of
462 Travis-Ci hours on the IPython organisation that was a necessary step.
463 Travis-Ci hours on the IPython organisation that was a necessary step.
463 :ghpull:`12900`.
464 :ghpull:`12900`.
464
465
465 - We have a new dependency: ``matplotlib-inline``, which try to extract
466 - We have a new dependency: ``matplotlib-inline``, which try to extract
466 matplotlib inline backend specific behavior. It is available on PyPI and
467 matplotlib inline backend specific behavior. It is available on PyPI and
467 conda-forge thus should not be a problem to upgrade to this version. If you
468 conda-forge thus should not be a problem to upgrade to this version. If you
468 are a package maintainer that might be an extra dependency to package first.
469 are a package maintainer that might be an extra dependency to package first.
469 :ghpull:`12817` (IPython 7.23.1 fix a typo that made this change fail)
470 :ghpull:`12817` (IPython 7.23.1 fix a typo that made this change fail)
470
471
471 In the addition/new feature category, ``display()`` now have a ``clear=True``
472 In the addition/new feature category, ``display()`` now have a ``clear=True``
472 option to clear the display if any further outputs arrives, allowing users to
473 option to clear the display if any further outputs arrives, allowing users to
473 avoid having to use ``clear_output()`` directly. :ghpull:`12823`.
474 avoid having to use ``clear_output()`` directly. :ghpull:`12823`.
474
475
475 In bug fixes category, this release fix an issue when printing tracebacks
476 In bug fixes category, this release fix an issue when printing tracebacks
476 containing Unicode characters :ghpull:`12758`.
477 containing Unicode characters :ghpull:`12758`.
477
478
478 In code cleanup category :ghpull:`12932` remove usage of some deprecated
479 In code cleanup category :ghpull:`12932` remove usage of some deprecated
479 functionality for compatibility with Python 3.10.
480 functionality for compatibility with Python 3.10.
480
481
481
482
482
483
483 Thanks
484 Thanks
484 ------
485 ------
485
486
486 Many thanks to all the contributors to this release you can find all individual
487 Many thanks to all the contributors to this release you can find all individual
487 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/86>`__.
488 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/86>`__.
488 In particular MrMino for responding to almost all new issues, and triaging many
489 In particular MrMino for responding to almost all new issues, and triaging many
489 of the old ones, as well as takluyver, minrk, willingc for reacting quikly when
490 of the old ones, as well as takluyver, minrk, willingc for reacting quikly when
490 we ran out of CI Hours.
491 we ran out of CI Hours.
491
492
492 Thanks as well to organisations, QuantStack (martinRenou and SylvainCorlay) for
493 Thanks as well to organisations, QuantStack (martinRenou and SylvainCorlay) for
493 extracting matplotlib inline backend into its own package, and the `D. E. Shaw group
494 extracting matplotlib inline backend into its own package, and the `D. E. Shaw group
494 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
495 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
495
496
496
497
497 .. _version 7.22:
498 .. _version 7.22:
498
499
499 IPython 7.22
500 IPython 7.22
500 ============
501 ============
501
502
502 Second release of IPython for 2021, mostly containing bug fixes. Here is a quick
503 Second release of IPython for 2021, mostly containing bug fixes. Here is a quick
503 rundown of the few changes.
504 rundown of the few changes.
504
505
505 - Fix some ``sys.excepthook`` shenanigan when embedding with qt, recommended if
506 - Fix some ``sys.excepthook`` shenanigan when embedding with qt, recommended if
506 you – for example – use `napari <https://napari.org>`__. :ghpull:`12842`.
507 you – for example – use `napari <https://napari.org>`__. :ghpull:`12842`.
507 - Fix bug when using the new ipdb ``%context`` magic :ghpull:`12844`
508 - Fix bug when using the new ipdb ``%context`` magic :ghpull:`12844`
508 - Couples of deprecation cleanup :ghpull:`12868`
509 - Couples of deprecation cleanup :ghpull:`12868`
509 - Update for new dpast.com api if you use the ``%pastbin`` magic. :ghpull:`12712`
510 - Update for new dpast.com api if you use the ``%pastbin`` magic. :ghpull:`12712`
510 - Remove support for numpy before 1.16. :ghpull:`12836`
511 - Remove support for numpy before 1.16. :ghpull:`12836`
511
512
512
513
513 Thanks
514 Thanks
514 ------
515 ------
515
516
516 We have a new team member that you should see more often on the IPython
517 We have a new team member that you should see more often on the IPython
517 repository, BΕ‚aΕΌej Michalik (@MrMino) have been doing regular contributions to
518 repository, BΕ‚aΕΌej Michalik (@MrMino) have been doing regular contributions to
518 IPython, and spent time replying to many issues and guiding new users to the
519 IPython, and spent time replying to many issues and guiding new users to the
519 codebase; they now have triage permissions to the IPython repository and we'll
520 codebase; they now have triage permissions to the IPython repository and we'll
520 work toward giving them more permission in the future.
521 work toward giving them more permission in the future.
521
522
522 Many thanks to all the contributors to this release you can find all individual
523 Many thanks to all the contributors to this release you can find all individual
523 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/84>`__.
524 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/84>`__.
524
525
525 Thanks as well to organisations, QuantStack for working on debugger
526 Thanks as well to organisations, QuantStack for working on debugger
526 compatibility for Xeus_python, and the `D. E. Shaw group
527 compatibility for Xeus_python, and the `D. E. Shaw group
527 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
528 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
528
529
529 .. _version 721:
530 .. _version 721:
530
531
531 IPython 7.21
532 IPython 7.21
532 ============
533 ============
533
534
534 IPython 7.21 is the first release we have back on schedule of one release every
535 IPython 7.21 is the first release we have back on schedule of one release every
535 month; it contains a number of minor fixes and improvements, notably, the new
536 month; it contains a number of minor fixes and improvements, notably, the new
536 context command for ipdb
537 context command for ipdb
537
538
538
539
539 New "context" command in ipdb
540 New "context" command in ipdb
540 -----------------------------
541 -----------------------------
541
542
542 It is now possible to change the number of lines shown in the backtrace
543 It is now possible to change the number of lines shown in the backtrace
543 information in ipdb using "context" command. :ghpull:`12826`
544 information in ipdb using "context" command. :ghpull:`12826`
544
545
545 (thanks @MrMino, there are other improvement from them on master).
546 (thanks @MrMino, there are other improvement from them on master).
546
547
547 Other notable changes in IPython 7.21
548 Other notable changes in IPython 7.21
548 -------------------------------------
549 -------------------------------------
549
550
550 - Fix some issues on new osx-arm64 :ghpull:`12804`, :ghpull:`12807`.
551 - Fix some issues on new osx-arm64 :ghpull:`12804`, :ghpull:`12807`.
551 - Compatibility with Xeus-Python for debugger protocol, :ghpull:`12809`
552 - Compatibility with Xeus-Python for debugger protocol, :ghpull:`12809`
552 - Misc docs fixes for compatibility and uniformity with Numpydoc.
553 - Misc docs fixes for compatibility and uniformity with Numpydoc.
553 :ghpull:`12824`
554 :ghpull:`12824`
554
555
555
556
556 Thanks
557 Thanks
557 ------
558 ------
558
559
559 Many thanks to all the contributors to this release you can find all individual
560 Many thanks to all the contributors to this release you can find all individual
560 contribution to this milestone `on github <https://github.com/ipython/ipython/milestone/83>`__.
561 contribution to this milestone `on github <https://github.com/ipython/ipython/milestone/83>`__.
561
562
562
563
563 .. _version 720:
564 .. _version 720:
564
565
565 IPython 7.20
566 IPython 7.20
566 ============
567 ============
567
568
568 IPython 7.20 is the accumulation of 3 month of work on IPython, spacing between
569 IPython 7.20 is the accumulation of 3 month of work on IPython, spacing between
569 IPython release have been increased from the usual once a month for various
570 IPython release have been increased from the usual once a month for various
570 reason.
571 reason.
571
572
572 - Mainly as I'm too busy and the effectively sole maintainer, and
573 - Mainly as I'm too busy and the effectively sole maintainer, and
573 - Second because not much changes happened before mid December.
574 - Second because not much changes happened before mid December.
574
575
575 The main driver for this release was the new version of Jedi 0.18 breaking API;
576 The main driver for this release was the new version of Jedi 0.18 breaking API;
576 which was taken care of in the master branch early in 2020 but not in 7.x as I
577 which was taken care of in the master branch early in 2020 but not in 7.x as I
577 though that by now 8.0 would be out.
578 though that by now 8.0 would be out.
578
579
579 The inclusion of a resolver in pip did not help and actually made things worse.
580 The inclusion of a resolver in pip did not help and actually made things worse.
580 If usually I would have simply pinned Jedi to ``<0.18``; this is not a solution
581 If usually I would have simply pinned Jedi to ``<0.18``; this is not a solution
581 anymore as now pip is free to install Jedi 0.18, and downgrade IPython.
582 anymore as now pip is free to install Jedi 0.18, and downgrade IPython.
582
583
583 I'll do my best to keep the regular release, but as the 8.0-dev branch and 7.x
584 I'll do my best to keep the regular release, but as the 8.0-dev branch and 7.x
584 are starting to diverge this is becoming difficult in particular with my limited
585 are starting to diverge this is becoming difficult in particular with my limited
585 time, so if you have any cycles to spare I'll appreciate your help to respond to
586 time, so if you have any cycles to spare I'll appreciate your help to respond to
586 issues and pushing 8.0 forward.
587 issues and pushing 8.0 forward.
587
588
588 Here are thus some of the changes for IPython 7.20.
589 Here are thus some of the changes for IPython 7.20.
589
590
590 - Support for PyQt5 >= 5.11 :ghpull:`12715`
591 - Support for PyQt5 >= 5.11 :ghpull:`12715`
591 - ``%reset`` remove imports more agressively :ghpull:`12718`
592 - ``%reset`` remove imports more agressively :ghpull:`12718`
592 - fix the ``%conda`` magic :ghpull:`12739`
593 - fix the ``%conda`` magic :ghpull:`12739`
593 - compatibility with Jedi 0.18, and bump minimum Jedi version. :ghpull:`12793`
594 - compatibility with Jedi 0.18, and bump minimum Jedi version. :ghpull:`12793`
594
595
595
596
596 .. _version 719:
597 .. _version 719:
597
598
598 IPython 7.19
599 IPython 7.19
599 ============
600 ============
600
601
601 IPython 7.19 accumulative two month of works, bug fixes and improvements, there
602 IPython 7.19 accumulative two month of works, bug fixes and improvements, there
602 was exceptionally no release last month.
603 was exceptionally no release last month.
603
604
604 - Fix to restore the ability to specify more than one extension using command
605 - Fix to restore the ability to specify more than one extension using command
605 line flags when using traitlets 5.0 :ghpull:`12543`
606 line flags when using traitlets 5.0 :ghpull:`12543`
606 - Docs docs formatting that make the install commands work on zsh
607 - Docs docs formatting that make the install commands work on zsh
607 :ghpull:`12587`
608 :ghpull:`12587`
608 - Always display the last frame in tracebacks even if hidden with
609 - Always display the last frame in tracebacks even if hidden with
609 ``__tracebackhide__`` :ghpull:`12601`
610 ``__tracebackhide__`` :ghpull:`12601`
610 - Avoid an issue where a callback can be registered multiple times.
611 - Avoid an issue where a callback can be registered multiple times.
611 :ghpull:`12625`
612 :ghpull:`12625`
612 - Avoid an issue in debugger mode where frames changes could be lost.
613 - Avoid an issue in debugger mode where frames changes could be lost.
613 :ghpull:`12627`
614 :ghpull:`12627`
614
615
615 - Never hide the frames that invoke a debugger, even if marked as hidden by
616 - Never hide the frames that invoke a debugger, even if marked as hidden by
616 ``__tracebackhide__`` :ghpull:`12631`
617 ``__tracebackhide__`` :ghpull:`12631`
617 - Fix calling the debugger in a recursive manner :ghpull:`12659`
618 - Fix calling the debugger in a recursive manner :ghpull:`12659`
618
619
619
620
620 A number of code changes have landed on master and we are getting close to
621 A number of code changes have landed on master and we are getting close to
621 enough new features and codebase improvement that a 8.0 start to make sens.
622 enough new features and codebase improvement that a 8.0 start to make sens.
622 For downstream packages, please start working on migrating downstream testing
623 For downstream packages, please start working on migrating downstream testing
623 away from iptest and using pytest, as nose will not work on Python 3.10 and we
624 away from iptest and using pytest, as nose will not work on Python 3.10 and we
624 will likely start removing it as a dependency for testing.
625 will likely start removing it as a dependency for testing.
625
626
626 .. _version 718:
627 .. _version 718:
627
628
628 IPython 7.18
629 IPython 7.18
629 ============
630 ============
630
631
631 IPython 7.18 is a minor release that mostly contains bugfixes.
632 IPython 7.18 is a minor release that mostly contains bugfixes.
632
633
633 - ``CRLF`` is now handled by magics my default; solving some issues due to copy
634 - ``CRLF`` is now handled by magics my default; solving some issues due to copy
634 pasting on windows. :ghpull:`12475`
635 pasting on windows. :ghpull:`12475`
635
636
636 - Requiring pexpect ``>=4.3`` as we are Python 3.7+ only and earlier version of
637 - Requiring pexpect ``>=4.3`` as we are Python 3.7+ only and earlier version of
637 pexpect will be incompatible. :ghpull:`12510`
638 pexpect will be incompatible. :ghpull:`12510`
638
639
639 - Minimum jedi version is now 0.16. :ghpull:`12488`
640 - Minimum jedi version is now 0.16. :ghpull:`12488`
640
641
641
642
642
643
643 .. _version 717:
644 .. _version 717:
644
645
645 IPython 7.17
646 IPython 7.17
646 ============
647 ============
647
648
648 IPython 7.17 brings a couple of new improvements to API and a couple of user
649 IPython 7.17 brings a couple of new improvements to API and a couple of user
649 facing changes to make the terminal experience more user friendly.
650 facing changes to make the terminal experience more user friendly.
650
651
651 :ghpull:`12407` introduces the ability to pass extra argument to the IPython
652 :ghpull:`12407` introduces the ability to pass extra argument to the IPython
652 debugger class; this is to help a new project from ``kmaork``
653 debugger class; this is to help a new project from ``kmaork``
653 (https://github.com/kmaork/madbg) to feature a fully remote debugger.
654 (https://github.com/kmaork/madbg) to feature a fully remote debugger.
654
655
655 :ghpull:`12410` finally remove support for 3.6, while the codebase is still
656 :ghpull:`12410` finally remove support for 3.6, while the codebase is still
656 technically compatible; IPython will not install on Python 3.6.
657 technically compatible; IPython will not install on Python 3.6.
657
658
658 lots of work on the debugger and hidden frames from ``@impact27`` in
659 lots of work on the debugger and hidden frames from ``@impact27`` in
659 :ghpull:`12437`, :ghpull:`12445`, :ghpull:`12460` and in particular
660 :ghpull:`12437`, :ghpull:`12445`, :ghpull:`12460` and in particular
660 :ghpull:`12453` which make the debug magic more robust at handling spaces.
661 :ghpull:`12453` which make the debug magic more robust at handling spaces.
661
662
662 Biggest API addition is code transformation which is done before code execution;
663 Biggest API addition is code transformation which is done before code execution;
663 IPython allows a number of hooks to catch non-valid Python syntax (magic, prompt
664 IPython allows a number of hooks to catch non-valid Python syntax (magic, prompt
664 stripping...etc). Transformers are usually called many time; typically:
665 stripping...etc). Transformers are usually called many time; typically:
665
666
666 - When trying to figure out whether the code is complete and valid (should we
667 - When trying to figure out whether the code is complete and valid (should we
667 insert a new line or execute ?)
668 insert a new line or execute ?)
668 - During actual code execution pass before giving the code to Python's
669 - During actual code execution pass before giving the code to Python's
669 ``exec``.
670 ``exec``.
670
671
671 This lead to issues when transformer might have had side effects; or do external
672 This lead to issues when transformer might have had side effects; or do external
672 queries. Starting with IPython 7.17 you can expect your transformer to be called
673 queries. Starting with IPython 7.17 you can expect your transformer to be called
673 less time.
674 less time.
674
675
675 Input transformers are now called only once in the execution path of
676 Input transformers are now called only once in the execution path of
676 `InteractiveShell`, allowing to register transformer that potentially have side
677 `InteractiveShell`, allowing to register transformer that potentially have side
677 effects (note that this is not recommended). Internal methods `should_run_async`, and
678 effects (note that this is not recommended). Internal methods `should_run_async`, and
678 `run_cell_async` now take a recommended optional `transformed_cell`, and
679 `run_cell_async` now take a recommended optional `transformed_cell`, and
679 `preprocessing_exc_tuple` parameters that will become mandatory at some point in
680 `preprocessing_exc_tuple` parameters that will become mandatory at some point in
680 the future; that is to say cells need to be explicitly transformed to be valid
681 the future; that is to say cells need to be explicitly transformed to be valid
681 Python syntax ahead of trying to run them. :ghpull:`12440`;
682 Python syntax ahead of trying to run them. :ghpull:`12440`;
682
683
683 ``input_transformers`` can now also have an attribute ``has_side_effects`` set
684 ``input_transformers`` can now also have an attribute ``has_side_effects`` set
684 to `True`, when this attribute is present; this will prevent the transformers
685 to `True`, when this attribute is present; this will prevent the transformers
685 from being ran when IPython is trying to guess whether the user input is
686 from being ran when IPython is trying to guess whether the user input is
686 complete. Note that this may means you will need to explicitly execute in some
687 complete. Note that this may means you will need to explicitly execute in some
687 case where your transformations are now not ran; but will not affect users with
688 case where your transformations are now not ran; but will not affect users with
688 no custom extensions.
689 no custom extensions.
689
690
690
691
691 API Changes
692 API Changes
692 -----------
693 -----------
693
694
694 Change of API and exposed objects automatically detected using `frappuccino
695 Change of API and exposed objects automatically detected using `frappuccino
695 <https://pypi.org/project/frappuccino/>`_
696 <https://pypi.org/project/frappuccino/>`_
696
697
697
698
698 The following items are new since 7.16.0::
699 The following items are new since 7.16.0::
699
700
700 + IPython.core.interactiveshell.InteractiveShell.get_local_scope(self, stack_depth)
701 + IPython.core.interactiveshell.InteractiveShell.get_local_scope(self, stack_depth)
701
702
702 The following signatures differ since 7.16.0::
703 The following signatures differ since 7.16.0::
703
704
704 - IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True)
705 - IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True)
705 + IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True, *, transformed_cell=None, preprocessing_exc_tuple=None)
706 + IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True, *, transformed_cell=None, preprocessing_exc_tuple=None)
706
707
707 - IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell)
708 - IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell)
708 + IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell, *, transformed_cell=None, preprocessing_exc_tuple=None)
709 + IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell, *, transformed_cell=None, preprocessing_exc_tuple=None)
709
710
710 - IPython.terminal.debugger.TerminalPdb.pt_init(self)
711 - IPython.terminal.debugger.TerminalPdb.pt_init(self)
711 + IPython.terminal.debugger.TerminalPdb.pt_init(self, pt_session_options=None)
712 + IPython.terminal.debugger.TerminalPdb.pt_init(self, pt_session_options=None)
712
713
713 This method was added::
714 This method was added::
714
715
715 + IPython.core.interactiveshell.InteractiveShell.get_local_scope
716 + IPython.core.interactiveshell.InteractiveShell.get_local_scope
716
717
717 Which is now also present on subclasses::
718 Which is now also present on subclasses::
718
719
719 + IPython.terminal.embed.InteractiveShellEmbed.get_local_scope
720 + IPython.terminal.embed.InteractiveShellEmbed.get_local_scope
720 + IPython.terminal.interactiveshell.TerminalInteractiveShell.get_local_scope
721 + IPython.terminal.interactiveshell.TerminalInteractiveShell.get_local_scope
721
722
722
723
723 .. _version 716:
724 .. _version 716:
724
725
725 IPython 7.16.1, 7.16.2
726 IPython 7.16.1, 7.16.2
726 ======================
727 ======================
727
728
728 IPython 7.16.1 was release immediately after 7.16.0 to fix a conda packaging issue.
729 IPython 7.16.1 was release immediately after 7.16.0 to fix a conda packaging issue.
729 The source is identical to 7.16.0 but the file permissions in the tar are different.
730 The source is identical to 7.16.0 but the file permissions in the tar are different.
730
731
731 IPython 7.16.2 pins jedi dependency to "<=0.17.2" which should prevent some
732 IPython 7.16.2 pins jedi dependency to "<=0.17.2" which should prevent some
732 issues for users still on python 3.6. This may not be sufficient as pip may
733 issues for users still on python 3.6. This may not be sufficient as pip may
733 still allow to downgrade IPython.
734 still allow to downgrade IPython.
734
735
735 Compatibility with Jedi > 0.17.2 was not added as this would have meant bumping
736 Compatibility with Jedi > 0.17.2 was not added as this would have meant bumping
736 the minimal version to >0.16.
737 the minimal version to >0.16.
737
738
738 IPython 7.16
739 IPython 7.16
739 ============
740 ============
740
741
741
742
742 The default traceback mode will now skip frames that are marked with
743 The default traceback mode will now skip frames that are marked with
743 ``__tracebackhide__ = True`` and show how many traceback frames have been
744 ``__tracebackhide__ = True`` and show how many traceback frames have been
744 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
745 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
745 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
746 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
746
747
747 The ipython debugger also now understands ``__tracebackhide__`` as well and will
748 The ipython debugger also now understands ``__tracebackhide__`` as well and will
748 skip hidden frames when displaying. Movement up and down the stack will skip the
749 skip hidden frames when displaying. Movement up and down the stack will skip the
749 hidden frames and will show how many frames were hidden. Internal IPython frames
750 hidden frames and will show how many frames were hidden. Internal IPython frames
750 are also now hidden by default. The behavior can be changed with the
751 are also now hidden by default. The behavior can be changed with the
751 ``skip_hidden`` while in the debugger, command and accepts "yes", "no", "true"
752 ``skip_hidden`` while in the debugger, command and accepts "yes", "no", "true"
752 and "false" case insensitive parameters.
753 and "false" case insensitive parameters.
753
754
754
755
755 Misc Noticeable changes:
756 Misc Noticeable changes:
756 ------------------------
757 ------------------------
757
758
758 - Exceptions are now (re)raised when running notebooks via the :magic:`%run`, helping to catch issues in workflows and
759 - Exceptions are now (re)raised when running notebooks via the :magic:`%run`, helping to catch issues in workflows and
759 pipelines. :ghpull:`12301`
760 pipelines. :ghpull:`12301`
760 - Fix inputhook for qt 5.15.0 :ghpull:`12355`
761 - Fix inputhook for qt 5.15.0 :ghpull:`12355`
761 - Fix wx inputhook :ghpull:`12375`
762 - Fix wx inputhook :ghpull:`12375`
762 - Add handling for malformed pathext env var (Windows) :ghpull:`12367`
763 - Add handling for malformed pathext env var (Windows) :ghpull:`12367`
763 - use $SHELL in system_piped :ghpull:`12360` for uniform behavior with
764 - use $SHELL in system_piped :ghpull:`12360` for uniform behavior with
764 ipykernel.
765 ipykernel.
765
766
766 Reproducible Build
767 Reproducible Build
767 ------------------
768 ------------------
768
769
769 IPython 7.15 reproducible build did not work, so we try again this month
770 IPython 7.15 reproducible build did not work, so we try again this month
770 :ghpull:`12358`.
771 :ghpull:`12358`.
771
772
772
773
773 API Changes
774 API Changes
774 -----------
775 -----------
775
776
776 Change of API and exposed objects automatically detected using `frappuccino
777 Change of API and exposed objects automatically detected using `frappuccino
777 <https://pypi.org/project/frappuccino/>`_ (still in beta):
778 <https://pypi.org/project/frappuccino/>`_ (still in beta):
778
779
779
780
780 The following items are new and mostly related to understanding ``__tracebackhide__``::
781 The following items are new and mostly related to understanding ``__tracebackhide__``::
781
782
782 + IPython.core.debugger.Pdb.do_down(self, arg)
783 + IPython.core.debugger.Pdb.do_down(self, arg)
783 + IPython.core.debugger.Pdb.do_skip_hidden(self, arg)
784 + IPython.core.debugger.Pdb.do_skip_hidden(self, arg)
784 + IPython.core.debugger.Pdb.do_up(self, arg)
785 + IPython.core.debugger.Pdb.do_up(self, arg)
785 + IPython.core.debugger.Pdb.hidden_frames(self, stack)
786 + IPython.core.debugger.Pdb.hidden_frames(self, stack)
786 + IPython.core.debugger.Pdb.stop_here(self, frame)
787 + IPython.core.debugger.Pdb.stop_here(self, frame)
787
788
788
789
789 The following items have been removed::
790 The following items have been removed::
790
791
791 - IPython.core.debugger.Pdb.new_do_down
792 - IPython.core.debugger.Pdb.new_do_down
792 - IPython.core.debugger.Pdb.new_do_up
793 - IPython.core.debugger.Pdb.new_do_up
793
794
794 Those were implementation details.
795 Those were implementation details.
795
796
796
797
797 .. _version 715:
798 .. _version 715:
798
799
799 IPython 7.15
800 IPython 7.15
800 ============
801 ============
801
802
802 IPython 7.15 brings a number of bug fixes and user facing improvements.
803 IPython 7.15 brings a number of bug fixes and user facing improvements.
803
804
804 Misc Noticeable changes:
805 Misc Noticeable changes:
805 ------------------------
806 ------------------------
806
807
807 - Long completion name have better elision in terminal :ghpull:`12284`
808 - Long completion name have better elision in terminal :ghpull:`12284`
808 - I've started to test on Python 3.9 :ghpull:`12307` and fix some errors.
809 - I've started to test on Python 3.9 :ghpull:`12307` and fix some errors.
809 - Hi DPI scaling of figures when using qt eventloop :ghpull:`12314`
810 - Hi DPI scaling of figures when using qt eventloop :ghpull:`12314`
810 - Document the ability to have systemwide configuration for IPython.
811 - Document the ability to have systemwide configuration for IPython.
811 :ghpull:`12328`
812 :ghpull:`12328`
812 - Fix issues with input autoformatting :ghpull:`12336`
813 - Fix issues with input autoformatting :ghpull:`12336`
813 - ``IPython.core.debugger.Pdb`` is now interruptible (:ghpull:`12168`, in 7.14
814 - ``IPython.core.debugger.Pdb`` is now interruptible (:ghpull:`12168`, in 7.14
814 but forgotten in release notes)
815 but forgotten in release notes)
815 - Video HTML attributes (:ghpull:`12212`, in 7.14 but forgotten in release
816 - Video HTML attributes (:ghpull:`12212`, in 7.14 but forgotten in release
816 notes)
817 notes)
817
818
818 Reproducible Build
819 Reproducible Build
819 ------------------
820 ------------------
820
821
821 Starting with IPython 7.15, I am attempting to provide reproducible builds,
822 Starting with IPython 7.15, I am attempting to provide reproducible builds,
822 that is to say you should be able from the source tree to generate an sdist
823 that is to say you should be able from the source tree to generate an sdist
823 and wheel that are identical byte for byte with the publish version on PyPI.
824 and wheel that are identical byte for byte with the publish version on PyPI.
824
825
825 I've only tested on a couple of machines so far and the process is relatively
826 I've only tested on a couple of machines so far and the process is relatively
826 straightforward, so this mean that IPython not only have a deterministic build
827 straightforward, so this mean that IPython not only have a deterministic build
827 process, but also I have either removed, or put under control all effects of
828 process, but also I have either removed, or put under control all effects of
828 the build environments on the final artifact. I encourage you to attempt the
829 the build environments on the final artifact. I encourage you to attempt the
829 build process on your machine as documented in :ref:`core_developer_guide`
830 build process on your machine as documented in :ref:`core_developer_guide`
830 and let me know if you do not obtain an identical artifact.
831 and let me know if you do not obtain an identical artifact.
831
832
832 While reproducible builds is critical to check that the supply chain of (open
833 While reproducible builds is critical to check that the supply chain of (open
833 source) software has not been compromised, it can also help to speedup many
834 source) software has not been compromised, it can also help to speedup many
834 of the build processes in large environment (conda, apt...) by allowing
835 of the build processes in large environment (conda, apt...) by allowing
835 better caching of intermediate build steps.
836 better caching of intermediate build steps.
836
837
837 Learn more on `<https://reproducible-builds.org/>`_. `Reflections on trusting
838 Learn more on `<https://reproducible-builds.org/>`_. `Reflections on trusting
838 trust <https://dl.acm.org/doi/10.1145/358198.358210>`_ is also one of the
839 trust <https://dl.acm.org/doi/10.1145/358198.358210>`_ is also one of the
839 cornerstone and recommended reads on this subject.
840 cornerstone and recommended reads on this subject.
840
841
841 .. note::
842 .. note::
842
843
843 The build commit from which the sdist is generated is also `signed
844 The build commit from which the sdist is generated is also `signed
844 <https://en.wikipedia.org/wiki/Digital_signature>`_, so you should be able to
845 <https://en.wikipedia.org/wiki/Digital_signature>`_, so you should be able to
845 check it has not been compromised, and the git repository is a `merkle-tree
846 check it has not been compromised, and the git repository is a `merkle-tree
846 <https://en.wikipedia.org/wiki/Merkle_tree>`_, you can check the consistency
847 <https://en.wikipedia.org/wiki/Merkle_tree>`_, you can check the consistency
847 with `git-fsck <https://git-scm.com/docs/git-fsck>`_ which you likely `want
848 with `git-fsck <https://git-scm.com/docs/git-fsck>`_ which you likely `want
848 to enable by default
849 to enable by default
849 <https://gist.github.com/mbbx6spp/14b86437e794bffb4120>`_.
850 <https://gist.github.com/mbbx6spp/14b86437e794bffb4120>`_.
850
851
851 NEP29: Last version to support Python 3.6
852 NEP29: Last version to support Python 3.6
852 -----------------------------------------
853 -----------------------------------------
853
854
854 IPython 7.15 will be the Last IPython version to officially support Python
855 IPython 7.15 will be the Last IPython version to officially support Python
855 3.6, as stated by `NumPy Enhancement Proposal 29
856 3.6, as stated by `NumPy Enhancement Proposal 29
856 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_. Starting with
857 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_. Starting with
857 next minor version of IPython I may stop testing on Python 3.6 and may stop
858 next minor version of IPython I may stop testing on Python 3.6 and may stop
858 publishing release artifacts that install on Python 3.6
859 publishing release artifacts that install on Python 3.6
859
860
860 Highlighted features
861 Highlighted features
861 --------------------
862 --------------------
862
863
863 Highlighted features are not new, but seem to not be widely known, this
864 Highlighted features are not new, but seem to not be widely known, this
864 section will help you discover in more narrative form what you can do with
865 section will help you discover in more narrative form what you can do with
865 IPython.
866 IPython.
866
867
867 Increase Tab Completion Menu Height
868 Increase Tab Completion Menu Height
868 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
869
870
870 In terminal IPython it is possible to increase the hight of the tab-completion
871 In terminal IPython it is possible to increase the hight of the tab-completion
871 menu. To do so set the value of
872 menu. To do so set the value of
872 :configtrait:`TerminalInteractiveShell.space_for_menu`, this will reserve more
873 :configtrait:`TerminalInteractiveShell.space_for_menu`, this will reserve more
873 space at the bottom of the screen for various kind of menus in IPython including
874 space at the bottom of the screen for various kind of menus in IPython including
874 tab completion and searching in history.
875 tab completion and searching in history.
875
876
876 Autoformat Code in the terminal
877 Autoformat Code in the terminal
877 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
878 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
878
879
879 If you have a preferred code formatter, you can configure IPython to
880 If you have a preferred code formatter, you can configure IPython to
880 reformat your code. Set the value of
881 reformat your code. Set the value of
881 :configtrait:`TerminalInteractiveShell.autoformatter` to for example ``'black'``
882 :configtrait:`TerminalInteractiveShell.autoformatter` to for example ``'black'``
882 and IPython will auto format your code when possible.
883 and IPython will auto format your code when possible.
883
884
884
885
885 .. _version 714:
886 .. _version 714:
886
887
887 IPython 7.14
888 IPython 7.14
888 ============
889 ============
889
890
890 IPython 7.14 is a minor release that fix a couple of bugs and prepare
891 IPython 7.14 is a minor release that fix a couple of bugs and prepare
891 compatibility with new or future versions of some libraries.
892 compatibility with new or future versions of some libraries.
892
893
893 Important changes:
894 Important changes:
894 ------------------
895 ------------------
895
896
896 - Fix compatibility with Sphinx 3+ :ghpull:`12235`
897 - Fix compatibility with Sphinx 3+ :ghpull:`12235`
897 - Remove deprecated matplotlib parameter usage, compatibility with matplotlib
898 - Remove deprecated matplotlib parameter usage, compatibility with matplotlib
898 3.3+ :`122250`
899 3.3+ :`122250`
899
900
900 Misc Changes
901 Misc Changes
901 ------------
902 ------------
902
903
903 - set ``.py`` extension when editing current buffer in vi/emacs. :ghpull:`12167`
904 - set ``.py`` extension when editing current buffer in vi/emacs. :ghpull:`12167`
904 - support for unicode identifiers in ``?``/``??`` :ghpull:`12208`
905 - support for unicode identifiers in ``?``/``??`` :ghpull:`12208`
905 - add extra options to the ``Video`` Rich objects :ghpull:`12212`
906 - add extra options to the ``Video`` Rich objects :ghpull:`12212`
906 - add pretty-printing to ``SimpleNamespace`` :ghpull:`12230`
907 - add pretty-printing to ``SimpleNamespace`` :ghpull:`12230`
907
908
908 IPython.core.debugger.Pdb is now interruptible
909 IPython.core.debugger.Pdb is now interruptible
909 ----------------------------------------------
910 ----------------------------------------------
910
911
911 A ``KeyboardInterrupt`` will now interrupt IPython's extended debugger, in order to make Jupyter able to interrupt it. (:ghpull:`12168`)
912 A ``KeyboardInterrupt`` will now interrupt IPython's extended debugger, in order to make Jupyter able to interrupt it. (:ghpull:`12168`)
912
913
913 Video HTML attributes
914 Video HTML attributes
914 ---------------------
915 ---------------------
915
916
916 Add an option to `IPython.display.Video` to change the attributes of the HTML display of the video (:ghpull:`12212`)
917 Add an option to `IPython.display.Video` to change the attributes of the HTML display of the video (:ghpull:`12212`)
917
918
918
919
919 Pending deprecated imports
920 Pending deprecated imports
920 --------------------------
921 --------------------------
921
922
922 Many object present in ``IPython.core.display`` are there for internal use only,
923 Many object present in ``IPython.core.display`` are there for internal use only,
923 and should already been imported from ``IPython.display`` by users and external
924 and should already been imported from ``IPython.display`` by users and external
924 libraries. Trying to import those from ``IPython.core.display`` is still possible
925 libraries. Trying to import those from ``IPython.core.display`` is still possible
925 but will trigger a
926 but will trigger a
926 deprecation warning in later versions of IPython and will become errors in the
927 deprecation warning in later versions of IPython and will become errors in the
927 future.
928 future.
928
929
929 This will simplify compatibility with other Python kernels (like Xeus-Python),
930 This will simplify compatibility with other Python kernels (like Xeus-Python),
930 and simplify code base.
931 and simplify code base.
931
932
932
933
933
934
934
935
935 .. _version 713:
936 .. _version 713:
936
937
937 IPython 7.13
938 IPython 7.13
938 ============
939 ============
939
940
940 IPython 7.13 is the final release of the 7.x branch since master is diverging
941 IPython 7.13 is the final release of the 7.x branch since master is diverging
941 toward an 8.0. Exiting new features have already been merged in 8.0 and will
942 toward an 8.0. Exiting new features have already been merged in 8.0 and will
942 not be available on the 7.x branch. All the changes below have been backported
943 not be available on the 7.x branch. All the changes below have been backported
943 from the master branch.
944 from the master branch.
944
945
945
946
946 - Fix inability to run PDB when inside an event loop :ghpull:`12141`
947 - Fix inability to run PDB when inside an event loop :ghpull:`12141`
947 - Fix ability to interrupt some processes on windows :ghpull:`12137`
948 - Fix ability to interrupt some processes on windows :ghpull:`12137`
948 - Fix debugger shortcuts :ghpull:`12132`
949 - Fix debugger shortcuts :ghpull:`12132`
949 - improve tab completion when inside a string by removing irrelevant elements :ghpull:`12128`
950 - improve tab completion when inside a string by removing irrelevant elements :ghpull:`12128`
950 - Fix display of filename tab completion when the path is long :ghpull:`12122`
951 - Fix display of filename tab completion when the path is long :ghpull:`12122`
951 - Many removal of Python 2 specific code path :ghpull:`12110`
952 - Many removal of Python 2 specific code path :ghpull:`12110`
952 - displaying wav files do not require NumPy anymore, and is 5x to 30x faster :ghpull:`12113`
953 - displaying wav files do not require NumPy anymore, and is 5x to 30x faster :ghpull:`12113`
953
954
954 See the list of all closed issues and pull request on `github
955 See the list of all closed issues and pull request on `github
955 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A7.13>`_.
956 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A7.13>`_.
956
957
957 .. _version 712:
958 .. _version 712:
958
959
959 IPython 7.12
960 IPython 7.12
960 ============
961 ============
961
962
962 IPython 7.12 is a minor update that mostly brings code cleanup, removal of
963 IPython 7.12 is a minor update that mostly brings code cleanup, removal of
963 longtime deprecated function and a couple update to documentation cleanup as well.
964 longtime deprecated function and a couple update to documentation cleanup as well.
964
965
965 Notable changes are the following:
966 Notable changes are the following:
966
967
967 - Exit non-zero when ipython is given a file path to run that doesn't exist :ghpull:`12074`
968 - Exit non-zero when ipython is given a file path to run that doesn't exist :ghpull:`12074`
968 - Test PR on ARM64 with Travis-CI :ghpull:`12073`
969 - Test PR on ARM64 with Travis-CI :ghpull:`12073`
969 - Update CI to work with latest Pytest :ghpull:`12086`
970 - Update CI to work with latest Pytest :ghpull:`12086`
970 - Add infrastructure to run ipykernel eventloop via trio :ghpull:`12097`
971 - Add infrastructure to run ipykernel eventloop via trio :ghpull:`12097`
971 - Support git blame ignore revs :ghpull:`12091`
972 - Support git blame ignore revs :ghpull:`12091`
972 - Start multi-line ``__repr__`` s on their own line :ghpull:`12099`
973 - Start multi-line ``__repr__`` s on their own line :ghpull:`12099`
973
974
974 .. _version 7111:
975 .. _version 7111:
975
976
976 IPython 7.11.1
977 IPython 7.11.1
977 ==============
978 ==============
978
979
979 A couple of deprecated functions (no-op) have been reintroduces in py3compat as
980 A couple of deprecated functions (no-op) have been reintroduces in py3compat as
980 Cython was still relying on them, and will be removed in a couple of versions.
981 Cython was still relying on them, and will be removed in a couple of versions.
981
982
982 .. _version 711:
983 .. _version 711:
983
984
984 IPython 7.11
985 IPython 7.11
985 ============
986 ============
986
987
987 IPython 7.11 received a couple of compatibility fixes and code cleanup.
988 IPython 7.11 received a couple of compatibility fixes and code cleanup.
988
989
989 A number of function in the ``py3compat`` have been removed; a number of types
990 A number of function in the ``py3compat`` have been removed; a number of types
990 in the IPython code base are now non-ambiguous and now always ``unicode``
991 in the IPython code base are now non-ambiguous and now always ``unicode``
991 instead of ``Union[Unicode,bytes]``; many of the relevant code path have thus
992 instead of ``Union[Unicode,bytes]``; many of the relevant code path have thus
992 been simplified/cleaned and types annotation added.
993 been simplified/cleaned and types annotation added.
993
994
994 IPython support several verbosity level from exceptions. ``xmode plain`` now
995 IPython support several verbosity level from exceptions. ``xmode plain`` now
995 support chained exceptions. :ghpull:`11999`
996 support chained exceptions. :ghpull:`11999`
996
997
997 We are starting to remove ``shell=True`` in some usages of subprocess. While not directly
998 We are starting to remove ``shell=True`` in some usages of subprocess. While not directly
998 a security issue (as IPython is made to run arbitrary code anyway) it is not good
999 a security issue (as IPython is made to run arbitrary code anyway) it is not good
999 practice and we'd like to show the example. :ghissue:`12023`. This discussion
1000 practice and we'd like to show the example. :ghissue:`12023`. This discussion
1000 was started by ``@mschwager`` thanks to a new auditing tool they are working on
1001 was started by ``@mschwager`` thanks to a new auditing tool they are working on
1001 with duo-labs (`dlint <https://github.com/duo-labs/dlint>`_).
1002 with duo-labs (`dlint <https://github.com/duo-labs/dlint>`_).
1002
1003
1003 Work around some bugs in Python 3.9 tokenizer :ghpull:`12057`
1004 Work around some bugs in Python 3.9 tokenizer :ghpull:`12057`
1004
1005
1005 IPython will now print its version after a crash. :ghpull:`11986`
1006 IPython will now print its version after a crash. :ghpull:`11986`
1006
1007
1007 This is likely the last release from the 7.x series that will see new feature.
1008 This is likely the last release from the 7.x series that will see new feature.
1008 The master branch will soon accept large code changes and thrilling new
1009 The master branch will soon accept large code changes and thrilling new
1009 features; the 7.x branch will only start to accept critical bug fixes, and
1010 features; the 7.x branch will only start to accept critical bug fixes, and
1010 update dependencies.
1011 update dependencies.
1011
1012
1012 .. _version 7102:
1013 .. _version 7102:
1013
1014
1014 IPython 7.10.2
1015 IPython 7.10.2
1015 ==============
1016 ==============
1016
1017
1017 IPython 7.10.2 fix a couple of extra incompatibility between IPython, ipdb,
1018 IPython 7.10.2 fix a couple of extra incompatibility between IPython, ipdb,
1018 asyncio and Prompt Toolkit 3.
1019 asyncio and Prompt Toolkit 3.
1019
1020
1020 .. _version 7101:
1021 .. _version 7101:
1021
1022
1022 IPython 7.10.1
1023 IPython 7.10.1
1023 ==============
1024 ==============
1024
1025
1025 IPython 7.10.1 fix a couple of incompatibilities with Prompt toolkit 3 (please
1026 IPython 7.10.1 fix a couple of incompatibilities with Prompt toolkit 3 (please
1026 update Prompt toolkit to 3.0.2 at least), and fixes some interaction with
1027 update Prompt toolkit to 3.0.2 at least), and fixes some interaction with
1027 headless IPython.
1028 headless IPython.
1028
1029
1029 .. _version 7100:
1030 .. _version 7100:
1030
1031
1031 IPython 7.10.0
1032 IPython 7.10.0
1032 ==============
1033 ==============
1033
1034
1034 IPython 7.10 is the first double digit minor release in the last decade, and
1035 IPython 7.10 is the first double digit minor release in the last decade, and
1035 first since the release of IPython 1.0, previous double digit minor release was
1036 first since the release of IPython 1.0, previous double digit minor release was
1036 in August 2009.
1037 in August 2009.
1037
1038
1038 We've been trying to give you regular release on the last Friday of every month
1039 We've been trying to give you regular release on the last Friday of every month
1039 for a guaranty of rapid access to bug fixes and new features.
1040 for a guaranty of rapid access to bug fixes and new features.
1040
1041
1041 Unlike the previous first few releases that have seen only a couple of code
1042 Unlike the previous first few releases that have seen only a couple of code
1042 changes, 7.10 bring a number of changes, new features and bugfixes.
1043 changes, 7.10 bring a number of changes, new features and bugfixes.
1043
1044
1044 Stop Support for Python 3.5 – Adopt NEP 29
1045 Stop Support for Python 3.5 – Adopt NEP 29
1045 ------------------------------------------
1046 ------------------------------------------
1046
1047
1047 IPython has decided to follow the informational `NEP 29
1048 IPython has decided to follow the informational `NEP 29
1048 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_ which layout a clear
1049 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_ which layout a clear
1049 policy as to which version of (C)Python and NumPy are supported.
1050 policy as to which version of (C)Python and NumPy are supported.
1050
1051
1051 We thus dropped support for Python 3.5, and cleaned up a number of code path
1052 We thus dropped support for Python 3.5, and cleaned up a number of code path
1052 that were Python-version dependant. If you are on 3.5 or earlier pip should
1053 that were Python-version dependant. If you are on 3.5 or earlier pip should
1053 automatically give you the latest compatible version of IPython so you do not
1054 automatically give you the latest compatible version of IPython so you do not
1054 need to pin to a given version.
1055 need to pin to a given version.
1055
1056
1056 Support for Prompt Toolkit 3.0
1057 Support for Prompt Toolkit 3.0
1057 ------------------------------
1058 ------------------------------
1058
1059
1059 Prompt Toolkit 3.0 was release a week before IPython 7.10 and introduces a few
1060 Prompt Toolkit 3.0 was release a week before IPython 7.10 and introduces a few
1060 breaking changes. We believe IPython 7.10 should be compatible with both Prompt
1061 breaking changes. We believe IPython 7.10 should be compatible with both Prompt
1061 Toolkit 2.x and 3.x, though it has not been extensively tested with 3.x so
1062 Toolkit 2.x and 3.x, though it has not been extensively tested with 3.x so
1062 please report any issues.
1063 please report any issues.
1063
1064
1064
1065
1065 Prompt Rendering Performance improvements
1066 Prompt Rendering Performance improvements
1066 -----------------------------------------
1067 -----------------------------------------
1067
1068
1068 Pull Request :ghpull:`11933` introduced an optimisation in the prompt rendering
1069 Pull Request :ghpull:`11933` introduced an optimisation in the prompt rendering
1069 logic that should decrease the resource usage of IPython when using the
1070 logic that should decrease the resource usage of IPython when using the
1070 _default_ configuration but could potentially introduce a regression of
1071 _default_ configuration but could potentially introduce a regression of
1071 functionalities if you are using a custom prompt.
1072 functionalities if you are using a custom prompt.
1072
1073
1073 We know assume if you haven't changed the default keybindings that the prompt
1074 We know assume if you haven't changed the default keybindings that the prompt
1074 **will not change** during the duration of your input – which is for example
1075 **will not change** during the duration of your input – which is for example
1075 not true when using vi insert mode that switches between `[ins]` and `[nor]`
1076 not true when using vi insert mode that switches between `[ins]` and `[nor]`
1076 for the current mode.
1077 for the current mode.
1077
1078
1078 If you are experiencing any issue let us know.
1079 If you are experiencing any issue let us know.
1079
1080
1080 Code autoformatting
1081 Code autoformatting
1081 -------------------
1082 -------------------
1082
1083
1083 The IPython terminal can now auto format your code just before entering a new
1084 The IPython terminal can now auto format your code just before entering a new
1084 line or executing a command. To do so use the
1085 line or executing a command. To do so use the
1085 ``--TerminalInteractiveShell.autoformatter`` option and set it to ``'black'``;
1086 ``--TerminalInteractiveShell.autoformatter`` option and set it to ``'black'``;
1086 if black is installed IPython will use black to format your code when possible.
1087 if black is installed IPython will use black to format your code when possible.
1087
1088
1088 IPython cannot always properly format your code; in particular it will
1089 IPython cannot always properly format your code; in particular it will
1089 auto formatting with *black* will only work if:
1090 auto formatting with *black* will only work if:
1090
1091
1091 - Your code does not contains magics or special python syntax.
1092 - Your code does not contains magics or special python syntax.
1092
1093
1093 - There is no code after your cursor.
1094 - There is no code after your cursor.
1094
1095
1095 The Black API is also still in motion; so this may not work with all versions of
1096 The Black API is also still in motion; so this may not work with all versions of
1096 black.
1097 black.
1097
1098
1098 It should be possible to register custom formatter, though the API is till in
1099 It should be possible to register custom formatter, though the API is till in
1099 flux.
1100 flux.
1100
1101
1101 Arbitrary Mimetypes Handing in Terminal (Aka inline images in terminal)
1102 Arbitrary Mimetypes Handing in Terminal (Aka inline images in terminal)
1102 -----------------------------------------------------------------------
1103 -----------------------------------------------------------------------
1103
1104
1104 When using IPython terminal it is now possible to register function to handle
1105 When using IPython terminal it is now possible to register function to handle
1105 arbitrary mimetypes. While rendering non-text based representation was possible in
1106 arbitrary mimetypes. While rendering non-text based representation was possible in
1106 many jupyter frontend; it was not possible in terminal IPython, as usually
1107 many jupyter frontend; it was not possible in terminal IPython, as usually
1107 terminal are limited to displaying text. As many terminal these days provide
1108 terminal are limited to displaying text. As many terminal these days provide
1108 escape sequences to display non-text; bringing this loved feature to IPython CLI
1109 escape sequences to display non-text; bringing this loved feature to IPython CLI
1109 made a lot of sens. This functionality will not only allow inline images; but
1110 made a lot of sens. This functionality will not only allow inline images; but
1110 allow opening of external program; for example ``mplayer`` to "display" sound
1111 allow opening of external program; for example ``mplayer`` to "display" sound
1111 files.
1112 files.
1112
1113
1113 So far only the hooks necessary for this are in place, but no default mime
1114 So far only the hooks necessary for this are in place, but no default mime
1114 renderers added; so inline images will only be available via extensions. We will
1115 renderers added; so inline images will only be available via extensions. We will
1115 progressively enable these features by default in the next few releases, and
1116 progressively enable these features by default in the next few releases, and
1116 contribution is welcomed.
1117 contribution is welcomed.
1117
1118
1118 We welcome any feedback on the API. See :ref:`shell_mimerenderer` for more
1119 We welcome any feedback on the API. See :ref:`shell_mimerenderer` for more
1119 informations.
1120 informations.
1120
1121
1121 This is originally based on work form in :ghpull:`10610` from @stephanh42
1122 This is originally based on work form in :ghpull:`10610` from @stephanh42
1122 started over two years ago, and still a lot need to be done.
1123 started over two years ago, and still a lot need to be done.
1123
1124
1124 MISC
1125 MISC
1125 ----
1126 ----
1126
1127
1127 - Completions can define their own ordering :ghpull:`11855`
1128 - Completions can define their own ordering :ghpull:`11855`
1128 - Enable Plotting in the same cell than the one that import matplotlib
1129 - Enable Plotting in the same cell than the one that import matplotlib
1129 :ghpull:`11916`
1130 :ghpull:`11916`
1130 - Allow to store and restore multiple variables at once :ghpull:`11930`
1131 - Allow to store and restore multiple variables at once :ghpull:`11930`
1131
1132
1132 You can see `all pull-requests <https://github.com/ipython/ipython/pulls?q=is%3Apr+milestone%3A7.10+is%3Aclosed>`_ for this release.
1133 You can see `all pull-requests <https://github.com/ipython/ipython/pulls?q=is%3Apr+milestone%3A7.10+is%3Aclosed>`_ for this release.
1133
1134
1134 API Changes
1135 API Changes
1135 -----------
1136 -----------
1136
1137
1137 Change of API and exposed objects automatically detected using `frappuccino <https://pypi.org/project/frappuccino/>`_ (still in beta):
1138 Change of API and exposed objects automatically detected using `frappuccino <https://pypi.org/project/frappuccino/>`_ (still in beta):
1138
1139
1139 The following items are new in IPython 7.10::
1140 The following items are new in IPython 7.10::
1140
1141
1141 + IPython.terminal.shortcuts.reformat_text_before_cursor(buffer, document, shell)
1142 + IPython.terminal.shortcuts.reformat_text_before_cursor(buffer, document, shell)
1142 + IPython.terminal.interactiveshell.PTK3
1143 + IPython.terminal.interactiveshell.PTK3
1143 + IPython.terminal.interactiveshell.black_reformat_handler(text_before_cursor)
1144 + IPython.terminal.interactiveshell.black_reformat_handler(text_before_cursor)
1144 + IPython.terminal.prompts.RichPromptDisplayHook.write_format_data(self, format_dict, md_dict='None')
1145 + IPython.terminal.prompts.RichPromptDisplayHook.write_format_data(self, format_dict, md_dict='None')
1145
1146
1146 The following items have been removed in 7.10::
1147 The following items have been removed in 7.10::
1147
1148
1148 - IPython.lib.pretty.DICT_IS_ORDERED
1149 - IPython.lib.pretty.DICT_IS_ORDERED
1149
1150
1150 The following signatures differ between versions::
1151 The following signatures differ between versions::
1151
1152
1152 - IPython.extensions.storemagic.restore_aliases(ip)
1153 - IPython.extensions.storemagic.restore_aliases(ip)
1153 + IPython.extensions.storemagic.restore_aliases(ip, alias='None')
1154 + IPython.extensions.storemagic.restore_aliases(ip, alias='None')
1154
1155
1155 Special Thanks
1156 Special Thanks
1156 --------------
1157 --------------
1157
1158
1158 - @stephanh42 who started the work on inline images in terminal 2 years ago
1159 - @stephanh42 who started the work on inline images in terminal 2 years ago
1159 - @augustogoulart who spent a lot of time triaging issues and responding to
1160 - @augustogoulart who spent a lot of time triaging issues and responding to
1160 users.
1161 users.
1161 - @con-f-use who is my (@Carreau) first sponsor on GitHub, as a reminder if you
1162 - @con-f-use who is my (@Carreau) first sponsor on GitHub, as a reminder if you
1162 like IPython, Jupyter and many other library of the SciPy stack you can
1163 like IPython, Jupyter and many other library of the SciPy stack you can
1163 donate to numfocus.org non profit
1164 donate to numfocus.org non profit
1164
1165
1165 .. _version 790:
1166 .. _version 790:
1166
1167
1167 IPython 7.9.0
1168 IPython 7.9.0
1168 =============
1169 =============
1169
1170
1170 IPython 7.9 is a small release with a couple of improvement and bug fixes.
1171 IPython 7.9 is a small release with a couple of improvement and bug fixes.
1171
1172
1172 - Xterm terminal title should be restored on exit :ghpull:`11910`
1173 - Xterm terminal title should be restored on exit :ghpull:`11910`
1173 - special variables ``_``,``__``, ``___`` are not set anymore when cache size
1174 - special variables ``_``,``__``, ``___`` are not set anymore when cache size
1174 is 0 or less. :ghpull:`11877`
1175 is 0 or less. :ghpull:`11877`
1175 - Autoreload should have regained some speed by using a new heuristic logic to
1176 - Autoreload should have regained some speed by using a new heuristic logic to
1176 find all objects needing reload. This should avoid large objects traversal
1177 find all objects needing reload. This should avoid large objects traversal
1177 like pandas dataframes. :ghpull:`11876`
1178 like pandas dataframes. :ghpull:`11876`
1178 - Get ready for Python 4. :ghpull:`11874`
1179 - Get ready for Python 4. :ghpull:`11874`
1179 - `%env` Magic now has heuristic to hide potentially sensitive values :ghpull:`11896`
1180 - `%env` Magic now has heuristic to hide potentially sensitive values :ghpull:`11896`
1180
1181
1181 This is a small release despite a number of Pull Request Pending that need to
1182 This is a small release despite a number of Pull Request Pending that need to
1182 be reviewed/worked on. Many of the core developers have been busy outside of
1183 be reviewed/worked on. Many of the core developers have been busy outside of
1183 IPython/Jupyter and we thanks all contributor for their patience; we'll work on
1184 IPython/Jupyter and we thanks all contributor for their patience; we'll work on
1184 these as soon as we have time.
1185 these as soon as we have time.
1185
1186
1186
1187
1187 .. _version780:
1188 .. _version780:
1188
1189
1189 IPython 7.8.0
1190 IPython 7.8.0
1190 =============
1191 =============
1191
1192
1192 IPython 7.8.0 contain a few bugfix and 2 new APIs:
1193 IPython 7.8.0 contain a few bugfix and 2 new APIs:
1193
1194
1194 - Enable changing the font color for LaTeX rendering :ghpull:`11840`
1195 - Enable changing the font color for LaTeX rendering :ghpull:`11840`
1195 - and Re-Expose some PDB API (see below)
1196 - and Re-Expose some PDB API (see below)
1196
1197
1197 Expose Pdb API
1198 Expose Pdb API
1198 --------------
1199 --------------
1199
1200
1200 Expose the built-in ``pdb.Pdb`` API. ``Pdb`` constructor arguments are generically
1201 Expose the built-in ``pdb.Pdb`` API. ``Pdb`` constructor arguments are generically
1201 exposed, regardless of python version.
1202 exposed, regardless of python version.
1202 Newly exposed arguments:
1203 Newly exposed arguments:
1203
1204
1204 - ``skip`` - Python 3.1+
1205 - ``skip`` - Python 3.1+
1205 - ``nosiginnt`` - Python 3.2+
1206 - ``nosiginnt`` - Python 3.2+
1206 - ``readrc`` - Python 3.6+
1207 - ``readrc`` - Python 3.6+
1207
1208
1208 Try it out::
1209 Try it out::
1209
1210
1210 from IPython.terminal.debugger import TerminalPdb
1211 from IPython.terminal.debugger import TerminalPdb
1211 pdb = TerminalPdb(skip=["skipthismodule"])
1212 pdb = TerminalPdb(skip=["skipthismodule"])
1212
1213
1213
1214
1214 See :ghpull:`11840`
1215 See :ghpull:`11840`
1215
1216
1216 .. _version770:
1217 .. _version770:
1217
1218
1218 IPython 7.7.0
1219 IPython 7.7.0
1219 =============
1220 =============
1220
1221
1221 IPython 7.7.0 contain multiple bug fixes and documentation updates; Here are a
1222 IPython 7.7.0 contain multiple bug fixes and documentation updates; Here are a
1222 few of the outstanding issue fixed:
1223 few of the outstanding issue fixed:
1223
1224
1224 - Fix a bug introduced in 7.6 where the ``%matplotlib`` magic would fail on
1225 - Fix a bug introduced in 7.6 where the ``%matplotlib`` magic would fail on
1225 previously acceptable arguments :ghpull:`11814`.
1226 previously acceptable arguments :ghpull:`11814`.
1226 - Fix the manage location on freebsd :ghpull:`11808`.
1227 - Fix the manage location on freebsd :ghpull:`11808`.
1227 - Fix error message about aliases after ``%reset`` call in ipykernel
1228 - Fix error message about aliases after ``%reset`` call in ipykernel
1228 :ghpull:`11806`
1229 :ghpull:`11806`
1229 - Fix Duplication completions in emacs :ghpull:`11803`
1230 - Fix Duplication completions in emacs :ghpull:`11803`
1230
1231
1231 We are planning to adopt `NEP29 <https://github.com/numpy/numpy/pull/14086>`_
1232 We are planning to adopt `NEP29 <https://github.com/numpy/numpy/pull/14086>`_
1232 (still currently in draft) which may make this minor version of IPython the
1233 (still currently in draft) which may make this minor version of IPython the
1233 last one to support Python 3.5 and will make the code base more aggressive
1234 last one to support Python 3.5 and will make the code base more aggressive
1234 toward removing compatibility with older versions of Python.
1235 toward removing compatibility with older versions of Python.
1235
1236
1236 GitHub now support to give only "Triage" permissions to users; if you'd like to
1237 GitHub now support to give only "Triage" permissions to users; if you'd like to
1237 help close stale issues and labels issues please reach to us with your GitHub
1238 help close stale issues and labels issues please reach to us with your GitHub
1238 Username and we'll add you to the triage team. It is a great way to start
1239 Username and we'll add you to the triage team. It is a great way to start
1239 contributing and a path toward getting commit rights.
1240 contributing and a path toward getting commit rights.
1240
1241
1241 .. _version761:
1242 .. _version761:
1242
1243
1243 IPython 7.6.1
1244 IPython 7.6.1
1244 =============
1245 =============
1245
1246
1246 IPython 7.6.1 contain a critical bugfix in the ``%timeit`` magic, which would
1247 IPython 7.6.1 contain a critical bugfix in the ``%timeit`` magic, which would
1247 crash on some inputs as a side effect of :ghpull:`11716`. See :ghpull:`11812`
1248 crash on some inputs as a side effect of :ghpull:`11716`. See :ghpull:`11812`
1248
1249
1249
1250
1250 .. _whatsnew760:
1251 .. _whatsnew760:
1251
1252
1252 IPython 7.6.0
1253 IPython 7.6.0
1253 =============
1254 =============
1254
1255
1255 IPython 7.6.0 contains a couple of bug fixes and number of small features
1256 IPython 7.6.0 contains a couple of bug fixes and number of small features
1256 additions as well as some compatibility with the current development version of
1257 additions as well as some compatibility with the current development version of
1257 Python 3.8.
1258 Python 3.8.
1258
1259
1259 - Add a ``-l`` option to :magic:`psearch` to list the available search
1260 - Add a ``-l`` option to :magic:`psearch` to list the available search
1260 types. :ghpull:`11672`
1261 types. :ghpull:`11672`
1261 - Support ``PathLike`` for ``DisplayObject`` and ``Image``. :ghpull:`11764`
1262 - Support ``PathLike`` for ``DisplayObject`` and ``Image``. :ghpull:`11764`
1262 - Configurability of timeout in the test suite for slow platforms.
1263 - Configurability of timeout in the test suite for slow platforms.
1263 :ghpull:`11756`
1264 :ghpull:`11756`
1264 - Accept any casing for matplotlib backend. :ghpull:`121748`
1265 - Accept any casing for matplotlib backend. :ghpull:`121748`
1265 - Properly skip test that requires numpy to be installed :ghpull:`11723`
1266 - Properly skip test that requires numpy to be installed :ghpull:`11723`
1266 - More support for Python 3.8 and positional only arguments (pep570)
1267 - More support for Python 3.8 and positional only arguments (pep570)
1267 :ghpull:`11720`
1268 :ghpull:`11720`
1268 - Unicode names for the completion are loaded lazily on first use which
1269 - Unicode names for the completion are loaded lazily on first use which
1269 should decrease startup time. :ghpull:`11693`
1270 should decrease startup time. :ghpull:`11693`
1270 - Autoreload now update the types of reloaded objects; this for example allow
1271 - Autoreload now update the types of reloaded objects; this for example allow
1271 pickling of reloaded objects. :ghpull:`11644`
1272 pickling of reloaded objects. :ghpull:`11644`
1272 - Fix a bug where ``%%time`` magic would suppress cell output. :ghpull:`11716`
1273 - Fix a bug where ``%%time`` magic would suppress cell output. :ghpull:`11716`
1273
1274
1274
1275
1275 Prepare migration to pytest (instead of nose) for testing
1276 Prepare migration to pytest (instead of nose) for testing
1276 ---------------------------------------------------------
1277 ---------------------------------------------------------
1277
1278
1278 Most of the work between 7.5 and 7.6 was to prepare the migration from our
1279 Most of the work between 7.5 and 7.6 was to prepare the migration from our
1279 testing framework to pytest. Most of the test suite should now work by simply
1280 testing framework to pytest. Most of the test suite should now work by simply
1280 issuing ``pytest`` from the root of the repository.
1281 issuing ``pytest`` from the root of the repository.
1281
1282
1282 The migration to pytest is just at its beginning. Many of our test still rely
1283 The migration to pytest is just at its beginning. Many of our test still rely
1283 on IPython-specific plugins for nose using pytest (doctest using IPython syntax
1284 on IPython-specific plugins for nose using pytest (doctest using IPython syntax
1284 is one example of this where test appear as "passing", while no code has been
1285 is one example of this where test appear as "passing", while no code has been
1285 ran). Many test also need to be updated like ``yield-test`` to be properly
1286 ran). Many test also need to be updated like ``yield-test`` to be properly
1286 parametrized tests.
1287 parametrized tests.
1287
1288
1288 Migration to pytest allowed me to discover a number of issues in our test
1289 Migration to pytest allowed me to discover a number of issues in our test
1289 suite; which was hiding a number of subtle issues – or not actually running
1290 suite; which was hiding a number of subtle issues – or not actually running
1290 some of the tests in our test suite – I have thus corrected many of those; like
1291 some of the tests in our test suite – I have thus corrected many of those; like
1291 improperly closed resources; or used of deprecated features. I also made use of
1292 improperly closed resources; or used of deprecated features. I also made use of
1292 the ``pytest --durations=...`` to find some of our slowest test and speed them
1293 the ``pytest --durations=...`` to find some of our slowest test and speed them
1293 up (our test suite can now be up to 10% faster). Pytest as also a variety of
1294 up (our test suite can now be up to 10% faster). Pytest as also a variety of
1294 plugins and flags which will make the code quality of IPython and the testing
1295 plugins and flags which will make the code quality of IPython and the testing
1295 experience better.
1296 experience better.
1296
1297
1297 Misc
1298 Misc
1298 ----
1299 ----
1299
1300
1300 We skipped the release of 7.6 at the end of May, but will attempt to get back
1301 We skipped the release of 7.6 at the end of May, but will attempt to get back
1301 on schedule. We are starting to think about making introducing backward
1302 on schedule. We are starting to think about making introducing backward
1302 incompatible change and start the 8.0 series.
1303 incompatible change and start the 8.0 series.
1303
1304
1304 Special Thanks to Gabriel (@gpotter2 on GitHub), who among other took care many
1305 Special Thanks to Gabriel (@gpotter2 on GitHub), who among other took care many
1305 of the remaining task for 7.4 and 7.5, like updating the website.
1306 of the remaining task for 7.4 and 7.5, like updating the website.
1306
1307
1307 .. _whatsnew750:
1308 .. _whatsnew750:
1308
1309
1309 IPython 7.5.0
1310 IPython 7.5.0
1310 =============
1311 =============
1311
1312
1312 IPython 7.5.0 consist mostly of bug-fixes, and documentation updates, with one
1313 IPython 7.5.0 consist mostly of bug-fixes, and documentation updates, with one
1313 minor new feature. The `Audio` display element can now be assigned an element
1314 minor new feature. The `Audio` display element can now be assigned an element
1314 id when displayed in browser. See :ghpull:`11670`
1315 id when displayed in browser. See :ghpull:`11670`
1315
1316
1316 The major outstanding bug fix correct a change of behavior that was introduce
1317 The major outstanding bug fix correct a change of behavior that was introduce
1317 in 7.4.0 where some cell magics would not be able to access or modify global
1318 in 7.4.0 where some cell magics would not be able to access or modify global
1318 scope when using the ``@needs_local_scope`` decorator. This was typically
1319 scope when using the ``@needs_local_scope`` decorator. This was typically
1319 encountered with the ``%%time`` and ``%%timeit`` magics. See :ghissue:`11659`
1320 encountered with the ``%%time`` and ``%%timeit`` magics. See :ghissue:`11659`
1320 and :ghpull:`11698`.
1321 and :ghpull:`11698`.
1321
1322
1322 .. _whatsnew740:
1323 .. _whatsnew740:
1323
1324
1324 IPython 7.4.0
1325 IPython 7.4.0
1325 =============
1326 =============
1326
1327
1327 Unicode name completions
1328 Unicode name completions
1328 ------------------------
1329 ------------------------
1329
1330
1330 Previously, we provided completion for a unicode name with its relative symbol.
1331 Previously, we provided completion for a unicode name with its relative symbol.
1331 With this, now IPython provides complete suggestions to unicode name symbols.
1332 With this, now IPython provides complete suggestions to unicode name symbols.
1332
1333
1333 As on the PR, if user types ``\LAT<tab>``, IPython provides a list of
1334 As on the PR, if user types ``\LAT<tab>``, IPython provides a list of
1334 possible completions. In this case, it would be something like::
1335 possible completions. In this case, it would be something like::
1335
1336
1336 'LATIN CAPITAL LETTER A',
1337 'LATIN CAPITAL LETTER A',
1337 'LATIN CAPITAL LETTER B',
1338 'LATIN CAPITAL LETTER B',
1338 'LATIN CAPITAL LETTER C',
1339 'LATIN CAPITAL LETTER C',
1339 'LATIN CAPITAL LETTER D',
1340 'LATIN CAPITAL LETTER D',
1340 ....
1341 ....
1341
1342
1342 This help to type unicode character that do not have short latex aliases, and
1343 This help to type unicode character that do not have short latex aliases, and
1343 have long unicode names. for example ``Ν°``, ``\GREEK CAPITAL LETTER HETA``.
1344 have long unicode names. for example ``Ν°``, ``\GREEK CAPITAL LETTER HETA``.
1344
1345
1345 This feature was contributed by Luciana Marques :ghpull:`11583`.
1346 This feature was contributed by Luciana Marques :ghpull:`11583`.
1346
1347
1347 Make audio normalization optional
1348 Make audio normalization optional
1348 ---------------------------------
1349 ---------------------------------
1349
1350
1350 Added 'normalize' argument to `IPython.display.Audio`. This argument applies
1351 Added 'normalize' argument to `IPython.display.Audio`. This argument applies
1351 when audio data is given as an array of samples. The default of `normalize=True`
1352 when audio data is given as an array of samples. The default of `normalize=True`
1352 preserves prior behavior of normalizing the audio to the maximum possible range.
1353 preserves prior behavior of normalizing the audio to the maximum possible range.
1353 Setting to `False` disables normalization.
1354 Setting to `False` disables normalization.
1354
1355
1355
1356
1356 Miscellaneous
1357 Miscellaneous
1357 -------------
1358 -------------
1358
1359
1359 - Fix improper acceptation of ``return`` outside of functions. :ghpull:`11641`.
1360 - Fix improper acceptation of ``return`` outside of functions. :ghpull:`11641`.
1360 - Fixed PyQt 5.11 backwards incompatibility causing sip import failure.
1361 - Fixed PyQt 5.11 backwards incompatibility causing sip import failure.
1361 :ghpull:`11613`.
1362 :ghpull:`11613`.
1362 - Fix Bug where ``type?`` would crash IPython. :ghpull:`1608`.
1363 - Fix Bug where ``type?`` would crash IPython. :ghpull:`1608`.
1363 - Allow to apply ``@needs_local_scope`` to cell magics for convenience.
1364 - Allow to apply ``@needs_local_scope`` to cell magics for convenience.
1364 :ghpull:`11542`.
1365 :ghpull:`11542`.
1365
1366
1366 .. _whatsnew730:
1367 .. _whatsnew730:
1367
1368
1368 IPython 7.3.0
1369 IPython 7.3.0
1369 =============
1370 =============
1370
1371
1371 .. _whatsnew720:
1372
1372
1373 IPython 7.3.0 bring several bug fixes and small improvements that you will
1373 IPython 7.3.0 bring several bug fixes and small improvements that you will
1374 described bellow.
1374 described bellow.
1375
1375
1376 The biggest change to this release is the implementation of the ``%conda`` and
1376 The biggest change to this release is the implementation of the ``%conda`` and
1377 ``%pip`` magics, that will attempt to install packages in the **current
1377 ``%pip`` magics, that will attempt to install packages in the **current
1378 environment**. You may still need to restart your interpreter or kernel for the
1378 environment**. You may still need to restart your interpreter or kernel for the
1379 change to be taken into account, but it should simplify installation of packages
1379 change to be taken into account, but it should simplify installation of packages
1380 into remote environment. Installing using pip/conda from the command line is
1380 into remote environment. Installing using pip/conda from the command line is
1381 still the prefer method.
1381 still the prefer method.
1382
1382
1383 The ``%pip`` magic was already present, but was only printing a warning; now it
1383 The ``%pip`` magic was already present, but was only printing a warning; now it
1384 will actually forward commands to pip.
1384 will actually forward commands to pip.
1385
1385
1386 Misc bug fixes and improvements:
1386 Misc bug fixes and improvements:
1387
1387
1388 - Compatibility with Python 3.8.
1388 - Compatibility with Python 3.8.
1389 - Do not expand shell variable in execution magics, and added the
1389 - Do not expand shell variable in execution magics, and added the
1390 ``no_var_expand`` decorator for magic requiring a similar functionality
1390 ``no_var_expand`` decorator for magic requiring a similar functionality
1391 :ghpull:`11516`
1391 :ghpull:`11516`
1392 - Add ``%pip`` and ``%conda`` magic :ghpull:`11524`
1392 - Add ``%pip`` and ``%conda`` magic :ghpull:`11524`
1393 - Re-initialize posix aliases after a ``%reset`` :ghpull:`11528`
1393 - Re-initialize posix aliases after a ``%reset`` :ghpull:`11528`
1394 - Allow the IPython command line to run ``*.ipynb`` files :ghpull:`11529`
1394 - Allow the IPython command line to run ``*.ipynb`` files :ghpull:`11529`
1395
1395
1396 .. _whatsnew720:
1397
1396 IPython 7.2.0
1398 IPython 7.2.0
1397 =============
1399 =============
1398
1400
1399 IPython 7.2.0 brings minor bugfixes, improvements, and new configuration options:
1401 IPython 7.2.0 brings minor bugfixes, improvements, and new configuration options:
1400
1402
1401 - Fix a bug preventing PySide2 GUI integration from working :ghpull:`11464`
1403 - Fix a bug preventing PySide2 GUI integration from working :ghpull:`11464`
1402 - Run CI on Mac OS ! :ghpull:`11471`
1404 - Run CI on Mac OS ! :ghpull:`11471`
1403 - Fix IPython "Demo" mode. :ghpull:`11498`
1405 - Fix IPython "Demo" mode. :ghpull:`11498`
1404 - Fix ``%run`` magic with path in name :ghpull:`11499`
1406 - Fix ``%run`` magic with path in name :ghpull:`11499`
1405 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
1407 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
1406 - Better rendering of signatures, especially long ones. :ghpull:`11505`
1408 - Better rendering of signatures, especially long ones. :ghpull:`11505`
1407 - Re-enable jedi by default if it's installed :ghpull:`11506`
1409 - Re-enable jedi by default if it's installed :ghpull:`11506`
1408 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
1410 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
1409
1411
1410
1412
1411 Added ability to show subclasses when using pinfo and other utilities
1413 Added ability to show subclasses when using pinfo and other utilities
1412 ---------------------------------------------------------------------
1414 ---------------------------------------------------------------------
1413
1415
1414 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
1416 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
1415
1417
1416 Special Thanks to Chris Mentzel of the Moore Foundation for this feature. Chris
1418 Special Thanks to Chris Mentzel of the Moore Foundation for this feature. Chris
1417 is one of the people who played a critical role in IPython/Jupyter getting
1419 is one of the people who played a critical role in IPython/Jupyter getting
1418 funding.
1420 funding.
1419
1421
1420 We are grateful for all the help Chris has given us over the years,
1422 We are grateful for all the help Chris has given us over the years,
1421 and we're now proud to have code contributed by Chris in IPython.
1423 and we're now proud to have code contributed by Chris in IPython.
1422
1424
1423 OSMagics.cd_force_quiet configuration option
1425 OSMagics.cd_force_quiet configuration option
1424 --------------------------------------------
1426 --------------------------------------------
1425
1427
1426 You can set this option to force the %cd magic to behave as if ``-q`` was passed:
1428 You can set this option to force the %cd magic to behave as if ``-q`` was passed::
1427 ::
1428
1429
1429 In [1]: cd /
1430 In [1]: cd /
1430 /
1431 /
1431
1432
1432 In [2]: %config OSMagics.cd_force_quiet = True
1433 In [2]: %config OSMagics.cd_force_quiet = True
1433
1434
1434 In [3]: cd /tmp
1435 In [3]: cd /tmp
1435
1436
1436 In [4]:
1437 In [4]:
1437
1438
1438 See :ghpull:`11491`
1439 See :ghpull:`11491`
1439
1440
1440 In vi editing mode, whether the prompt includes the current vi mode can now be configured
1441 In vi editing mode, whether the prompt includes the current vi mode can now be configured
1441 -----------------------------------------------------------------------------------------
1442 -----------------------------------------------------------------------------------------
1442
1443
1443 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
1444 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
1444 (default: True) to control this feature. See :ghpull:`11492`
1445 (default: True) to control this feature. See :ghpull:`11492`
1445
1446
1446 .. _whatsnew710:
1447 .. _whatsnew710:
1447
1448
1448 IPython 7.1.0
1449 IPython 7.1.0
1449 =============
1450 =============
1450
1451
1451 IPython 7.1.0 is the first minor release after 7.0.0 and mostly brings fixes to
1452 IPython 7.1.0 is the first minor release after 7.0.0 and mostly brings fixes to
1452 new features, internal refactoring, and fixes for regressions that happened during the 6.x->7.x
1453 new features, internal refactoring, and fixes for regressions that happened during the 6.x->7.x
1453 transition. It also brings **Compatibility with Python 3.7.1**, as we're
1454 transition. It also brings **Compatibility with Python 3.7.1**, as we're
1454 unwillingly relying on a bug in CPython.
1455 unwillingly relying on a bug in CPython.
1455
1456
1456 New Core Dev:
1457 New Core Dev:
1457
1458
1458 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
1459 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
1459 work on prompt_toolkit, and we'd like to recognise his impact by giving him
1460 work on prompt_toolkit, and we'd like to recognise his impact by giving him
1460 commit rights. :ghissue:`11397`
1461 commit rights. :ghissue:`11397`
1461
1462
1462 Notable Changes
1463 Notable Changes
1463
1464
1464 - Major update of "latex to unicode" tab completion map (see below)
1465 - Major update of "latex to unicode" tab completion map (see below)
1465
1466
1466 Notable New Features:
1467 Notable New Features:
1467
1468
1468 - Restore functionality and documentation of the **sphinx directive**, which
1469 - Restore functionality and documentation of the **sphinx directive**, which
1469 is now stricter (fail on error by daefault), has new configuration options,
1470 is now stricter (fail on error by daefault), has new configuration options,
1470 has a brand new documentation page :ref:`ipython_directive` (which needs
1471 has a brand new documentation page :ref:`ipython_directive` (which needs
1471 some cleanup). It is also now *tested* so we hope to have less regressions.
1472 some cleanup). It is also now *tested* so we hope to have less regressions.
1472 :ghpull:`11402`
1473 :ghpull:`11402`
1473
1474
1474 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
1475 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
1475 allowing a custom width and height to be set instead of using the video's
1476 allowing a custom width and height to be set instead of using the video's
1476 width and height. :ghpull:`11353`
1477 width and height. :ghpull:`11353`
1477
1478
1478 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
1479 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
1479
1480
1480 - Allow Dynamic switching of editing mode between vi/emacs and show
1481 - Allow Dynamic switching of editing mode between vi/emacs and show
1481 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
1482 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
1482 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
1483 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
1483 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically switch
1484 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically switch
1484 between modes.
1485 between modes.
1485
1486
1486
1487
1487 Notable Fixes:
1488 Notable Fixes:
1488
1489
1489 - Fix entering of **multi-line blocks in terminal** IPython, and various
1490 - Fix entering of **multi-line blocks in terminal** IPython, and various
1490 crashes in the new input transformation machinery :ghpull:`11354`,
1491 crashes in the new input transformation machinery :ghpull:`11354`,
1491 :ghpull:`11356`, :ghpull:`11358`. These also fix a **Compatibility bug
1492 :ghpull:`11356`, :ghpull:`11358`. These also fix a **Compatibility bug
1492 with Python 3.7.1**.
1493 with Python 3.7.1**.
1493
1494
1494 - Fix moving through generator stack in ipdb :ghpull:`11266`
1495 - Fix moving through generator stack in ipdb :ghpull:`11266`
1495
1496
1496 - %Magic command arguments now support quoting. :ghpull:`11330`
1497 - %Magic command arguments now support quoting. :ghpull:`11330`
1497
1498
1498 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
1499 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
1499
1500
1500 - Remove implicit dependency on ``ipython_genutils`` :ghpull:`11317`
1501 - Remove implicit dependency on ``ipython_genutils`` :ghpull:`11317`
1501
1502
1502 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
1503 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
1503 mode. :ghpull:`11382`
1504 mode. :ghpull:`11382`
1504
1505
1505 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
1506 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
1506 nested code blocks :ghpull:`11418`
1507 nested code blocks :ghpull:`11418`
1507
1508
1508 - Fix instructions for custom shortcuts :ghpull:`11426`
1509 - Fix instructions for custom shortcuts :ghpull:`11426`
1509
1510
1510
1511
1511 Notable Internals improvements:
1512 Notable Internals improvements:
1512
1513
1513 - Use of ``os.scandir`` (Python 3 only) to speed up some file system operations.
1514 - Use of ``os.scandir`` (Python 3 only) to speed up some file system operations.
1514 :ghpull:`11365`
1515 :ghpull:`11365`
1515
1516
1516 - use ``perf_counter`` instead of ``clock`` for more precise
1517 - use ``perf_counter`` instead of ``clock`` for more precise
1517 timing results with ``%time`` :ghpull:`11376`
1518 timing results with ``%time`` :ghpull:`11376`
1518
1519
1519 Many thanks to all the contributors and in particular to ``bartskowron`` and
1520 Many thanks to all the contributors and in particular to ``bartskowron`` and
1520 ``tonyfast`` who handled some pretty complicated bugs in the input machinery. We
1521 ``tonyfast`` who handled some pretty complicated bugs in the input machinery. We
1521 had a number of first time contributors and maybe hacktoberfest participants that
1522 had a number of first time contributors and maybe hacktoberfest participants that
1522 made significant contributions and helped us free some time to focus on more
1523 made significant contributions and helped us free some time to focus on more
1523 complicated bugs.
1524 complicated bugs.
1524
1525
1525 You
1526 You
1526 can see all the closed issues and Merged PR, new features and fixes `here
1527 can see all the closed issues and Merged PR, new features and fixes `here
1527 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
1528 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
1528
1529
1529 Unicode Completion update
1530 Unicode Completion update
1530 -------------------------
1531 -------------------------
1531
1532
1532 In IPython 7.1 the Unicode completion map has been updated and synchronized with
1533 In IPython 7.1 the Unicode completion map has been updated and synchronized with
1533 the Julia language.
1534 the Julia language.
1534
1535
1535 Added and removed character characters:
1536 Added and removed character characters:
1536
1537
1537 ``\jmath`` (``Θ·``), ``\\underleftrightarrow`` (U+034D, combining) have been
1538 ``\jmath`` (``Θ·``), ``\\underleftrightarrow`` (U+034D, combining) have been
1538 added, while ``\\textasciicaron`` have been removed
1539 added, while ``\\textasciicaron`` have been removed
1539
1540
1540 Some sequences have seen their prefix removed:
1541 Some sequences have seen their prefix removed:
1541
1542
1542 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
1543 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
1543 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
1544 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
1544 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
1545 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
1545 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
1546 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
1546
1547
1547 Some sequences have seen their prefix shortened:
1548 Some sequences have seen their prefix shortened:
1548
1549
1549 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
1550 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
1550 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
1551 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
1551 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
1552 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
1552 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
1553 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
1553
1554
1554 A couple of characters had their sequence simplified:
1555 A couple of characters had their sequence simplified:
1555
1556
1556 - ``Γ°``, type ``\dh<tab>``, instead of ``\eth<tab>``
1557 - ``Γ°``, type ``\dh<tab>``, instead of ``\eth<tab>``
1557 - ``Δ§``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
1558 - ``Δ§``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
1558 - ``ΙΈ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
1559 - ``ΙΈ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
1559 - ``Ο΄``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
1560 - ``Ο΄``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
1560 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
1561 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
1561 - ``β„Ž``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
1562 - ``β„Ž``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
1562
1563
1563 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
1564 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
1564
1565
1565 A couple of sequences have been updated:
1566 A couple of sequences have been updated:
1566
1567
1567 - ``\varepsilon`` now gives ``Ι›`` (GREEK SMALL LETTER EPSILON) instead of ``Ξ΅`` (GREEK LUNATE EPSILON SYMBOL),
1568 - ``\varepsilon`` now gives ``Ι›`` (GREEK SMALL LETTER EPSILON) instead of ``Ξ΅`` (GREEK LUNATE EPSILON SYMBOL),
1568 - ``\underbar`` now gives U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
1569 - ``\underbar`` now gives U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
1569
1570
1570
1571
1571 .. _whatsnew700:
1572 .. _whatsnew700:
1572
1573
1573 IPython 7.0.0
1574 IPython 7.0.0
1574 =============
1575 =============
1575
1576
1576 Released Thursday September 27th, 2018
1577 Released Thursday September 27th, 2018
1577
1578
1578 IPython 7 includes major feature improvements.
1579 IPython 7 includes major feature improvements.
1579 This is also the second major version of IPython to support only
1580 This is also the second major version of IPython to support only
1580 Python 3 – starting at Python 3.4. Python 2 is still community-supported
1581 Python 3 – starting at Python 3.4. Python 2 is still community-supported
1581 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
1582 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
1582 is on Jan 1st 2020.
1583 is on Jan 1st 2020.
1583
1584
1584 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
1585 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
1585 backported more than `70 Pull-Requests
1586 backported more than `70 Pull-Requests
1586 <https://github.com/ipython/ipython/pulls?page=3&q=is%3Apr+sort%3Aupdated-desc+author%3Aapp%2Fmeeseeksdev++5.x&utf8=%E2%9C%93>`_, but there are still many PRs that required manual work. This is an area of the project where you can easily contribute by looking for `PRs that still need manual backport <https://github.com/ipython/ipython/issues?q=label%3A%22Still+Needs+Manual+Backport%22+is%3Aclosed+sort%3Aupdated-desc>`_
1587 <https://github.com/ipython/ipython/pulls?page=3&q=is%3Apr+sort%3Aupdated-desc+author%3Aapp%2Fmeeseeksdev++5.x&utf8=%E2%9C%93>`_, but there are still many PRs that required manual work. This is an area of the project where you can easily contribute by looking for `PRs that still need manual backport <https://github.com/ipython/ipython/issues?q=label%3A%22Still+Needs+Manual+Backport%22+is%3Aclosed+sort%3Aupdated-desc>`_
1587
1588
1588 The IPython 6.x branch will likely not see any further release unless critical
1589 The IPython 6.x branch will likely not see any further release unless critical
1589 bugs are found.
1590 bugs are found.
1590
1591
1591 Make sure you have pip > 9.0 before upgrading. You should be able to update by running:
1592 Make sure you have pip > 9.0 before upgrading. You should be able to update by running:
1592
1593
1593 .. code::
1594 .. code::
1594
1595
1595 pip install ipython --upgrade
1596 pip install ipython --upgrade
1596
1597
1597 .. only:: ipydev
1598 .. only:: ipydev
1598
1599
1599 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
1600 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
1600 version, use pip ``--pre`` flag.
1601 version, use pip ``--pre`` flag.
1601
1602
1602 .. code::
1603 .. code::
1603
1604
1604 pip install ipython --upgrade --pre
1605 pip install ipython --upgrade --pre
1605
1606
1606
1607
1607 Or, if you have conda installed:
1608 Or, if you have conda installed:
1608
1609
1609 .. code::
1610 .. code::
1610
1611
1611 conda install ipython
1612 conda install ipython
1612
1613
1613
1614
1614
1615
1615 Prompt Toolkit 2.0
1616 Prompt Toolkit 2.0
1616 ------------------
1617 ------------------
1617
1618
1618 IPython 7.0+ now uses ``prompt_toolkit 2.0``. If you still need to use an earlier
1619 IPython 7.0+ now uses ``prompt_toolkit 2.0``. If you still need to use an earlier
1619 ``prompt_toolkit`` version, you may need to pin IPython to ``<7.0``.
1620 ``prompt_toolkit`` version, you may need to pin IPython to ``<7.0``.
1620
1621
1621 Autowait: Asynchronous REPL
1622 Autowait: Asynchronous REPL
1622 ---------------------------
1623 ---------------------------
1623
1624
1624 Staring with IPython 7.0 on Python 3.6+, IPython can automatically ``await``
1625 Staring with IPython 7.0 on Python 3.6+, IPython can automatically ``await``
1625 top level code. You should not need to access an event loop or runner
1626 top level code. You should not need to access an event loop or runner
1626 yourself. To learn more, read the :ref:`autoawait` section of our docs, see
1627 yourself. To learn more, read the :ref:`autoawait` section of our docs, see
1627 :ghpull:`11265`, or try the following code::
1628 :ghpull:`11265`, or try the following code::
1628
1629
1629 Python 3.6.0
1630 Python 3.6.0
1630 Type 'copyright', 'credits' or 'license' for more information
1631 Type 'copyright', 'credits' or 'license' for more information
1631 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
1632 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
1632
1633
1633 In [1]: import aiohttp
1634 In [1]: import aiohttp
1634 ...: result = aiohttp.get('https://api.github.com')
1635 ...: result = aiohttp.get('https://api.github.com')
1635
1636
1636 In [2]: response = await result
1637 In [2]: response = await result
1637 <pause for a few 100s ms>
1638 <pause for a few 100s ms>
1638
1639
1639 In [3]: await response.json()
1640 In [3]: await response.json()
1640 Out[3]:
1641 Out[3]:
1641 {'authorizations_url': 'https://api.github.com/authorizations',
1642 {'authorizations_url': 'https://api.github.com/authorizations',
1642 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
1643 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
1643 ...
1644 ...
1644 }
1645 }
1645
1646
1646 .. note::
1647 .. note::
1647
1648
1648 Async integration is experimental code, behavior may change or be removed
1649 Async integration is experimental code, behavior may change or be removed
1649 between Python and IPython versions without warnings.
1650 between Python and IPython versions without warnings.
1650
1651
1651 Integration is by default with `asyncio`, but other libraries can be configured --
1652 Integration is by default with `asyncio`, but other libraries can be configured --
1652 like ``curio`` or ``trio`` -- to improve concurrency in the REPL::
1653 like ``curio`` or ``trio`` -- to improve concurrency in the REPL::
1653
1654
1654 In [1]: %autoawait trio
1655 In [1]: %autoawait trio
1655
1656
1656 In [2]: import trio
1657 In [2]: import trio
1657
1658
1658 In [3]: async def child(i):
1659 In [3]: async def child(i):
1659 ...: print(" child %s goes to sleep"%i)
1660 ...: print(" child %s goes to sleep"%i)
1660 ...: await trio.sleep(2)
1661 ...: await trio.sleep(2)
1661 ...: print(" child %s wakes up"%i)
1662 ...: print(" child %s wakes up"%i)
1662
1663
1663 In [4]: print('parent start')
1664 In [4]: print('parent start')
1664 ...: async with trio.open_nursery() as n:
1665 ...: async with trio.open_nursery() as n:
1665 ...: for i in range(3):
1666 ...: for i in range(3):
1666 ...: n.spawn(child, i)
1667 ...: n.spawn(child, i)
1667 ...: print('parent end')
1668 ...: print('parent end')
1668 parent start
1669 parent start
1669 child 2 goes to sleep
1670 child 2 goes to sleep
1670 child 0 goes to sleep
1671 child 0 goes to sleep
1671 child 1 goes to sleep
1672 child 1 goes to sleep
1672 <about 2 seconds pause>
1673 <about 2 seconds pause>
1673 child 2 wakes up
1674 child 2 wakes up
1674 child 1 wakes up
1675 child 1 wakes up
1675 child 0 wakes up
1676 child 0 wakes up
1676 parent end
1677 parent end
1677
1678
1678 See :ref:`autoawait` for more information.
1679 See :ref:`autoawait` for more information.
1679
1680
1680
1681
1681 Asynchronous code in a Notebook interface or any other frontend using the
1682 Asynchronous code in a Notebook interface or any other frontend using the
1682 Jupyter Protocol will require further updates to the IPykernel package.
1683 Jupyter Protocol will require further updates to the IPykernel package.
1683
1684
1684 Non-Asynchronous code
1685 Non-Asynchronous code
1685 ~~~~~~~~~~~~~~~~~~~~~
1686 ~~~~~~~~~~~~~~~~~~~~~
1686
1687
1687 As the internal API of IPython is now asynchronous, IPython needs to run under
1688 As the internal API of IPython is now asynchronous, IPython needs to run under
1688 an event loop. In order to allow many workflows, (like using the :magic:`%run`
1689 an event loop. In order to allow many workflows, (like using the :magic:`%run`
1689 magic, or copy-pasting code that explicitly starts/stop event loop), when
1690 magic, or copy-pasting code that explicitly starts/stop event loop), when
1690 top-level code is detected as not being asynchronous, IPython code is advanced
1691 top-level code is detected as not being asynchronous, IPython code is advanced
1691 via a pseudo-synchronous runner, and may not advance pending tasks.
1692 via a pseudo-synchronous runner, and may not advance pending tasks.
1692
1693
1693 Change to Nested Embed
1694 Change to Nested Embed
1694 ~~~~~~~~~~~~~~~~~~~~~~
1695 ~~~~~~~~~~~~~~~~~~~~~~
1695
1696
1696 The introduction of the ability to run async code had some effect on the
1697 The introduction of the ability to run async code had some effect on the
1697 ``IPython.embed()`` API. By default, embed will not allow you to run asynchronous
1698 ``IPython.embed()`` API. By default, embed will not allow you to run asynchronous
1698 code unless an event loop is specified.
1699 code unless an event loop is specified.
1699
1700
1700 Effects on Magics
1701 Effects on Magics
1701 ~~~~~~~~~~~~~~~~~
1702 ~~~~~~~~~~~~~~~~~
1702
1703
1703 Some magics will not work with async until they're updated.
1704 Some magics will not work with async until they're updated.
1704 Contributions welcome.
1705 Contributions welcome.
1705
1706
1706 Expected Future changes
1707 Expected Future changes
1707 ~~~~~~~~~~~~~~~~~~~~~~~
1708 ~~~~~~~~~~~~~~~~~~~~~~~
1708
1709
1709 We expect more internal but public IPython functions to become ``async``, and
1710 We expect more internal but public IPython functions to become ``async``, and
1710 will likely end up having a persistent event loop while IPython is running.
1711 will likely end up having a persistent event loop while IPython is running.
1711
1712
1712 Thanks
1713 Thanks
1713 ~~~~~~
1714 ~~~~~~
1714
1715
1715 This release took more than a year in the making.
1716 This release took more than a year in the making.
1716 The code was rebased a number of
1717 The code was rebased a number of
1717 times; leading to commit authorship that may have been lost in the final
1718 times; leading to commit authorship that may have been lost in the final
1718 Pull-Request. Huge thanks to many people for contribution, discussion, code,
1719 Pull-Request. Huge thanks to many people for contribution, discussion, code,
1719 documentation, use-cases: dalejung, danielballan, ellisonbg, fperez, gnestor,
1720 documentation, use-cases: dalejung, danielballan, ellisonbg, fperez, gnestor,
1720 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
1721 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
1721
1722
1722
1723
1723 Autoreload Improvement
1724 Autoreload Improvement
1724 ----------------------
1725 ----------------------
1725
1726
1726 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
1727 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
1727 classes. Earlier, only methods existing as of the initial import were being
1728 classes. Earlier, only methods existing as of the initial import were being
1728 tracked and updated.
1729 tracked and updated.
1729
1730
1730 This new feature helps dual environment development - Jupyter+IDE - where the
1731 This new feature helps dual environment development - Jupyter+IDE - where the
1731 code gradually moves from notebook cells to package files as it gets
1732 code gradually moves from notebook cells to package files as it gets
1732 structured.
1733 structured.
1733
1734
1734 **Example**: An instance of the class ``MyClass`` will be able to access the
1735 **Example**: An instance of the class ``MyClass`` will be able to access the
1735 method ``cube()`` after it is uncommented and the file ``file1.py`` is saved on
1736 method ``cube()`` after it is uncommented and the file ``file1.py`` is saved on
1736 disk.
1737 disk.
1737
1738
1738
1739
1739 .. code::
1740 .. code::
1740
1741
1741 # notebook
1742 # notebook
1742
1743
1743 from mymodule import MyClass
1744 from mymodule import MyClass
1744 first = MyClass(5)
1745 first = MyClass(5)
1745
1746
1746 .. code::
1747 .. code::
1747
1748
1748 # mymodule/file1.py
1749 # mymodule/file1.py
1749
1750
1750 class MyClass:
1751 class MyClass:
1751
1752
1752 def __init__(self, a=10):
1753 def __init__(self, a=10):
1753 self.a = a
1754 self.a = a
1754
1755
1755 def square(self):
1756 def square(self):
1756 print('compute square')
1757 print('compute square')
1757 return self.a*self.a
1758 return self.a*self.a
1758
1759
1759 # def cube(self):
1760 # def cube(self):
1760 # print('compute cube')
1761 # print('compute cube')
1761 # return self.a*self.a*self.a
1762 # return self.a*self.a*self.a
1762
1763
1763
1764
1764
1765
1765
1766
1766 Misc
1767 Misc
1767 ----
1768 ----
1768
1769
1769 The autoindent feature that was deprecated in 5.x was re-enabled and
1770 The autoindent feature that was deprecated in 5.x was re-enabled and
1770 un-deprecated in :ghpull:`11257`
1771 un-deprecated in :ghpull:`11257`
1771
1772
1772 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
1773 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
1773 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
1774 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
1774
1775
1775
1776
1776 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
1777 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
1777 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
1778 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
1778 the given code is non-zero (thus halting execution of further cells in a
1779 the given code is non-zero (thus halting execution of further cells in a
1779 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
1780 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
1780
1781
1781
1782
1782 Deprecations
1783 Deprecations
1783 ------------
1784 ------------
1784
1785
1785 A couple of unused functions and methods have been deprecated and will be removed
1786 A couple of unused functions and methods have been deprecated and will be removed
1786 in future versions:
1787 in future versions:
1787
1788
1788 - ``IPython.utils.io.raw_print_err``
1789 - ``IPython.utils.io.raw_print_err``
1789 - ``IPython.utils.io.raw_print``
1790 - ``IPython.utils.io.raw_print``
1790
1791
1791
1792
1792 Backwards incompatible changes
1793 Backwards incompatible changes
1793 ------------------------------
1794 ------------------------------
1794
1795
1795 * The API for transforming input before it is parsed as Python code has been
1796 * The API for transforming input before it is parsed as Python code has been
1796 completely redesigned: any custom input transformations will need to be
1797 completely redesigned: any custom input transformations will need to be
1797 rewritten. See :doc:`/config/inputtransforms` for details of the new API.
1798 rewritten. See :doc:`/config/inputtransforms` for details of the new API.
General Comments 0
You need to be logged in to leave comments. Login now