##// END OF EJS Templates
Allow decorator frames to be marked as skippable....
Matthias Bussonnier -
Show More
@@ -1,972 +1,1094 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5
6 This is an extension to PDB which adds a number of new features.
7 Note that there is also the `IPython.terminal.debugger` class which provides UI
8 improvements.
9
10 We also strongly recommend to use this via the `ipdb` package, which provides
11 extra configuration options.
12
13 Amoung other this subclass of PDB expose here:
14 - support many IPython magics like pdef/psource.
15 - allow to hide some frames in tracebacks
16 - allow to skip some frames.
17
18 The skipping and hiding frames are configurable via the `skip_predicates`
19 command.
20
21 By default, frames from readonly files will be hidden, frames containing
22 ``__tracebackhide__=True`` will be hidden.
23
24 Frames containing ``__debuggerskip__`` will be stepped over, frames who's parent
25 frames value of ``__debuggerskip__`` is ``True`` will be skipped.
26
27 >>> def helper_1():
28 ... print("don't step in me")
29 ...
30 ...
31 ... def helper_2():
32 ... print("in me neither")
33 ...
34
35 One can define a decorator that wrap a function between the two helpers:
36
37 >>> def pdb_skipped_decorator(function):
38 ...
39 ...
40 ... def wrapped_fn(*args, **kwargs):
41 ... __debuggerskip__ = True
42 ... helper_1()
43 ... __debuggerskip__ = False
44 ... result = function(*args, **kwargs)
45 ... __debuggerskip__ = True
46 ... helper_2()
47 ... return result
48 ...
49 ... return wrapped_fn
50
51 When decorating a function, ipdb will directly step into ``bar()`` by
52 default:
53
54 >>> @foo_decorator
55 ... def bar(x, y):
56 ... return x * y
57
58
59 You can toggle the behavior with
60
61 ipdb> skip_predicates debuggerskip false
62
63 or configure it in your ``.pdbrc``
64
65
66
67 Licencse
68 --------
69
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
70 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
71 the command line completion of other programs which include this isn't
7 damaged.
72 damaged.
8
73
9 In the future, this class will be expanded with improvements over the standard
74 In the future, this class will be expanded with improvements over the standard
10 pdb.
75 pdb.
11
76
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
77 The original code in this file is mainly lifted out of cmd.py in Python 2.2,
13 changes. Licensing should therefore be under the standard Python terms. For
78 with minor changes. Licensing should therefore be under the standard Python
14 details on the PSF (Python Software Foundation) standard license, see:
79 terms. For details on the PSF (Python Software Foundation) standard license,
80 see:
15
81
16 https://docs.python.org/2/license.html
82 https://docs.python.org/2/license.html
83
84
85 All the changes since then are under the same license as IPython.
86
17 """
87 """
18
88
19 #*****************************************************************************
89 #*****************************************************************************
20 #
90 #
21 # This file is licensed under the PSF license.
91 # This file is licensed under the PSF license.
22 #
92 #
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
93 # Copyright (C) 2001 Python Software Foundation, www.python.org
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
94 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
25 #
95 #
26 #
96 #
27 #*****************************************************************************
97 #*****************************************************************************
28
98
29 import bdb
99 import bdb
30 import functools
100 import functools
31 import inspect
101 import inspect
32 import linecache
102 import linecache
33 import sys
103 import sys
34 import warnings
104 import warnings
35 import re
105 import re
36 import os
106 import os
37
107
38 from IPython import get_ipython
108 from IPython import get_ipython
39 from IPython.utils import PyColorize
109 from IPython.utils import PyColorize
40 from IPython.utils import coloransi, py3compat
110 from IPython.utils import coloransi, py3compat
41 from IPython.core.excolors import exception_colors
111 from IPython.core.excolors import exception_colors
42 from IPython.testing.skipdoctest import skip_doctest
112 from IPython.testing.skipdoctest import skip_doctest
43
113
44
114
45 prompt = 'ipdb> '
115 prompt = 'ipdb> '
46
116
47 # We have to check this directly from sys.argv, config struct not yet available
117 # We have to check this directly from sys.argv, config struct not yet available
48 from pdb import Pdb as OldPdb
118 from pdb import Pdb as OldPdb
49
119
50 # Allow the set_trace code to operate outside of an ipython instance, even if
120 # Allow the set_trace code to operate outside of an ipython instance, even if
51 # it does so with some limitations. The rest of this support is implemented in
121 # it does so with some limitations. The rest of this support is implemented in
52 # the Tracer constructor.
122 # the Tracer constructor.
53
123
124 DEBUGGERSKIP = "__debuggerskip__"
125
54
126
55 def make_arrow(pad):
127 def make_arrow(pad):
56 """generate the leading arrow in front of traceback or debugger"""
128 """generate the leading arrow in front of traceback or debugger"""
57 if pad >= 2:
129 if pad >= 2:
58 return '-'*(pad-2) + '> '
130 return '-'*(pad-2) + '> '
59 elif pad == 1:
131 elif pad == 1:
60 return '>'
132 return '>'
61 return ''
133 return ''
62
134
63
135
64 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
136 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
65 """Exception hook which handles `BdbQuit` exceptions.
137 """Exception hook which handles `BdbQuit` exceptions.
66
138
67 All other exceptions are processed using the `excepthook`
139 All other exceptions are processed using the `excepthook`
68 parameter.
140 parameter.
69 """
141 """
70 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
142 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
71 DeprecationWarning, stacklevel=2)
143 DeprecationWarning, stacklevel=2)
72 if et == bdb.BdbQuit:
144 if et == bdb.BdbQuit:
73 print('Exiting Debugger.')
145 print('Exiting Debugger.')
74 elif excepthook is not None:
146 elif excepthook is not None:
75 excepthook(et, ev, tb)
147 excepthook(et, ev, tb)
76 else:
148 else:
77 # Backwards compatibility. Raise deprecation warning?
149 # Backwards compatibility. Raise deprecation warning?
78 BdbQuit_excepthook.excepthook_ori(et, ev, tb)
150 BdbQuit_excepthook.excepthook_ori(et, ev, tb)
79
151
80
152
81 def BdbQuit_IPython_excepthook(self, et, ev, tb, tb_offset=None):
153 def BdbQuit_IPython_excepthook(self, et, ev, tb, tb_offset=None):
82 warnings.warn(
154 warnings.warn(
83 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
155 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
84 DeprecationWarning, stacklevel=2)
156 DeprecationWarning, stacklevel=2)
85 print('Exiting Debugger.')
157 print('Exiting Debugger.')
86
158
87
159
88 class Tracer(object):
160 class Tracer(object):
89 """
161 """
90 DEPRECATED
162 DEPRECATED
91
163
92 Class for local debugging, similar to pdb.set_trace.
164 Class for local debugging, similar to pdb.set_trace.
93
165
94 Instances of this class, when called, behave like pdb.set_trace, but
166 Instances of this class, when called, behave like pdb.set_trace, but
95 providing IPython's enhanced capabilities.
167 providing IPython's enhanced capabilities.
96
168
97 This is implemented as a class which must be initialized in your own code
169 This is implemented as a class which must be initialized in your own code
98 and not as a standalone function because we need to detect at runtime
170 and not as a standalone function because we need to detect at runtime
99 whether IPython is already active or not. That detection is done in the
171 whether IPython is already active or not. That detection is done in the
100 constructor, ensuring that this code plays nicely with a running IPython,
172 constructor, ensuring that this code plays nicely with a running IPython,
101 while functioning acceptably (though with limitations) if outside of it.
173 while functioning acceptably (though with limitations) if outside of it.
102 """
174 """
103
175
104 @skip_doctest
176 @skip_doctest
105 def __init__(self, colors=None):
177 def __init__(self, colors=None):
106 """
178 """
107 DEPRECATED
179 DEPRECATED
108
180
109 Create a local debugger instance.
181 Create a local debugger instance.
110
182
111 Parameters
183 Parameters
112 ----------
184 ----------
113 colors : str, optional
185 colors : str, optional
114 The name of the color scheme to use, it must be one of IPython's
186 The name of the color scheme to use, it must be one of IPython's
115 valid color schemes. If not given, the function will default to
187 valid color schemes. If not given, the function will default to
116 the current IPython scheme when running inside IPython, and to
188 the current IPython scheme when running inside IPython, and to
117 'NoColor' otherwise.
189 'NoColor' otherwise.
118
190
119 Examples
191 Examples
120 --------
192 --------
121 ::
193 ::
122
194
123 from IPython.core.debugger import Tracer; debug_here = Tracer()
195 from IPython.core.debugger import Tracer; debug_here = Tracer()
124
196
125 Later in your code::
197 Later in your code::
126
198
127 debug_here() # -> will open up the debugger at that point.
199 debug_here() # -> will open up the debugger at that point.
128
200
129 Once the debugger activates, you can use all of its regular commands to
201 Once the debugger activates, you can use all of its regular commands to
130 step through code, set breakpoints, etc. See the pdb documentation
202 step through code, set breakpoints, etc. See the pdb documentation
131 from the Python standard library for usage details.
203 from the Python standard library for usage details.
132 """
204 """
133 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
205 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
134 "`IPython.core.debugger.Pdb.set_trace()`",
206 "`IPython.core.debugger.Pdb.set_trace()`",
135 DeprecationWarning, stacklevel=2)
207 DeprecationWarning, stacklevel=2)
136
208
137 ip = get_ipython()
209 ip = get_ipython()
138 if ip is None:
210 if ip is None:
139 # Outside of ipython, we set our own exception hook manually
211 # Outside of ipython, we set our own exception hook manually
140 sys.excepthook = functools.partial(BdbQuit_excepthook,
212 sys.excepthook = functools.partial(BdbQuit_excepthook,
141 excepthook=sys.excepthook)
213 excepthook=sys.excepthook)
142 def_colors = 'NoColor'
214 def_colors = 'NoColor'
143 else:
215 else:
144 # In ipython, we use its custom exception handler mechanism
216 # In ipython, we use its custom exception handler mechanism
145 def_colors = ip.colors
217 def_colors = ip.colors
146 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
218 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
147
219
148 if colors is None:
220 if colors is None:
149 colors = def_colors
221 colors = def_colors
150
222
151 # The stdlib debugger internally uses a modified repr from the `repr`
223 # The stdlib debugger internally uses a modified repr from the `repr`
152 # module, that limits the length of printed strings to a hardcoded
224 # module, that limits the length of printed strings to a hardcoded
153 # limit of 30 characters. That much trimming is too aggressive, let's
225 # limit of 30 characters. That much trimming is too aggressive, let's
154 # at least raise that limit to 80 chars, which should be enough for
226 # at least raise that limit to 80 chars, which should be enough for
155 # most interactive uses.
227 # most interactive uses.
156 try:
228 try:
157 from reprlib import aRepr
229 from reprlib import aRepr
158 aRepr.maxstring = 80
230 aRepr.maxstring = 80
159 except:
231 except:
160 # This is only a user-facing convenience, so any error we encounter
232 # This is only a user-facing convenience, so any error we encounter
161 # here can be warned about but can be otherwise ignored. These
233 # here can be warned about but can be otherwise ignored. These
162 # printouts will tell us about problems if this API changes
234 # printouts will tell us about problems if this API changes
163 import traceback
235 import traceback
164 traceback.print_exc()
236 traceback.print_exc()
165
237
166 self.debugger = Pdb(colors)
238 self.debugger = Pdb(colors)
167
239
168 def __call__(self):
240 def __call__(self):
169 """Starts an interactive debugger at the point where called.
241 """Starts an interactive debugger at the point where called.
170
242
171 This is similar to the pdb.set_trace() function from the std lib, but
243 This is similar to the pdb.set_trace() function from the std lib, but
172 using IPython's enhanced debugger."""
244 using IPython's enhanced debugger."""
173
245
174 self.debugger.set_trace(sys._getframe().f_back)
246 self.debugger.set_trace(sys._getframe().f_back)
175
247
176
248
177 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
249 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
178
250
179
251
180 def strip_indentation(multiline_string):
252 def strip_indentation(multiline_string):
181 return RGX_EXTRA_INDENT.sub('', multiline_string)
253 return RGX_EXTRA_INDENT.sub('', multiline_string)
182
254
183
255
184 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
256 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
185 """Make new_fn have old_fn's doc string. This is particularly useful
257 """Make new_fn have old_fn's doc string. This is particularly useful
186 for the ``do_...`` commands that hook into the help system.
258 for the ``do_...`` commands that hook into the help system.
187 Adapted from from a comp.lang.python posting
259 Adapted from from a comp.lang.python posting
188 by Duncan Booth."""
260 by Duncan Booth."""
189 def wrapper(*args, **kw):
261 def wrapper(*args, **kw):
190 return new_fn(*args, **kw)
262 return new_fn(*args, **kw)
191 if old_fn.__doc__:
263 if old_fn.__doc__:
192 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
264 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
193 return wrapper
265 return wrapper
194
266
195
267
196 class Pdb(OldPdb):
268 class Pdb(OldPdb):
197 """Modified Pdb class, does not load readline.
269 """Modified Pdb class, does not load readline.
198
270
199 for a standalone version that uses prompt_toolkit, see
271 for a standalone version that uses prompt_toolkit, see
200 `IPython.terminal.debugger.TerminalPdb` and
272 `IPython.terminal.debugger.TerminalPdb` and
201 `IPython.terminal.debugger.set_trace()`
273 `IPython.terminal.debugger.set_trace()`
202
274
203
275
204 This debugger can hide and skip frames that are tagged according to some predicates.
276 This debugger can hide and skip frames that are tagged according to some predicates.
205 See the `skip_predicates` commands.
277 See the `skip_predicates` commands.
206
278
207 """
279 """
208
280
209 default_predicates = {"tbhide": True, "readonly": False, "ipython_internal": True}
281 default_predicates = {
282 "tbhide": True,
283 "readonly": False,
284 "ipython_internal": True,
285 "debuggerskip": True,
286 }
210
287
211 def __init__(self, color_scheme=None, completekey=None,
288 def __init__(self, color_scheme=None, completekey=None,
212 stdin=None, stdout=None, context=5, **kwargs):
289 stdin=None, stdout=None, context=5, **kwargs):
213 """Create a new IPython debugger.
290 """Create a new IPython debugger.
214
291
215 Parameters
292 Parameters
216 ----------
293 ----------
217 color_scheme : default None
294 color_scheme : default None
218 Deprecated, do not use.
295 Deprecated, do not use.
219 completekey : default None
296 completekey : default None
220 Passed to pdb.Pdb.
297 Passed to pdb.Pdb.
221 stdin : default None
298 stdin : default None
222 Passed to pdb.Pdb.
299 Passed to pdb.Pdb.
223 stdout : default None
300 stdout : default None
224 Passed to pdb.Pdb.
301 Passed to pdb.Pdb.
225 context : int
302 context : int
226 Number of lines of source code context to show when
303 Number of lines of source code context to show when
227 displaying stacktrace information.
304 displaying stacktrace information.
228 **kwargs
305 **kwargs
229 Passed to pdb.Pdb.
306 Passed to pdb.Pdb.
230
307
231 Notes
308 Notes
232 -----
309 -----
233 The possibilities are python version dependent, see the python
310 The possibilities are python version dependent, see the python
234 docs for more info.
311 docs for more info.
235 """
312 """
236
313
237 # Parent constructor:
314 # Parent constructor:
238 try:
315 try:
239 self.context = int(context)
316 self.context = int(context)
240 if self.context <= 0:
317 if self.context <= 0:
241 raise ValueError("Context must be a positive integer")
318 raise ValueError("Context must be a positive integer")
242 except (TypeError, ValueError) as e:
319 except (TypeError, ValueError) as e:
243 raise ValueError("Context must be a positive integer") from e
320 raise ValueError("Context must be a positive integer") from e
244
321
245 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
322 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
246 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
323 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
247
324
248 # IPython changes...
325 # IPython changes...
249 self.shell = get_ipython()
326 self.shell = get_ipython()
250
327
251 if self.shell is None:
328 if self.shell is None:
252 save_main = sys.modules['__main__']
329 save_main = sys.modules['__main__']
253 # No IPython instance running, we must create one
330 # No IPython instance running, we must create one
254 from IPython.terminal.interactiveshell import \
331 from IPython.terminal.interactiveshell import \
255 TerminalInteractiveShell
332 TerminalInteractiveShell
256 self.shell = TerminalInteractiveShell.instance()
333 self.shell = TerminalInteractiveShell.instance()
257 # needed by any code which calls __import__("__main__") after
334 # needed by any code which calls __import__("__main__") after
258 # the debugger was entered. See also #9941.
335 # the debugger was entered. See also #9941.
259 sys.modules["__main__"] = save_main
336 sys.modules["__main__"] = save_main
260
337
261 if color_scheme is not None:
338 if color_scheme is not None:
262 warnings.warn(
339 warnings.warn(
263 "The `color_scheme` argument is deprecated since version 5.1",
340 "The `color_scheme` argument is deprecated since version 5.1",
264 DeprecationWarning, stacklevel=2)
341 DeprecationWarning, stacklevel=2)
265 else:
342 else:
266 color_scheme = self.shell.colors
343 color_scheme = self.shell.colors
267
344
268 self.aliases = {}
345 self.aliases = {}
269
346
270 # Create color table: we copy the default one from the traceback
347 # Create color table: we copy the default one from the traceback
271 # module and add a few attributes needed for debugging
348 # module and add a few attributes needed for debugging
272 self.color_scheme_table = exception_colors()
349 self.color_scheme_table = exception_colors()
273
350
274 # shorthands
351 # shorthands
275 C = coloransi.TermColors
352 C = coloransi.TermColors
276 cst = self.color_scheme_table
353 cst = self.color_scheme_table
277
354
278 cst['NoColor'].colors.prompt = C.NoColor
355 cst['NoColor'].colors.prompt = C.NoColor
279 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
356 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
280 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
357 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
281
358
282 cst['Linux'].colors.prompt = C.Green
359 cst['Linux'].colors.prompt = C.Green
283 cst['Linux'].colors.breakpoint_enabled = C.LightRed
360 cst['Linux'].colors.breakpoint_enabled = C.LightRed
284 cst['Linux'].colors.breakpoint_disabled = C.Red
361 cst['Linux'].colors.breakpoint_disabled = C.Red
285
362
286 cst['LightBG'].colors.prompt = C.Blue
363 cst['LightBG'].colors.prompt = C.Blue
287 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
364 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
288 cst['LightBG'].colors.breakpoint_disabled = C.Red
365 cst['LightBG'].colors.breakpoint_disabled = C.Red
289
366
290 cst['Neutral'].colors.prompt = C.Blue
367 cst['Neutral'].colors.prompt = C.Blue
291 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
368 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
292 cst['Neutral'].colors.breakpoint_disabled = C.Red
369 cst['Neutral'].colors.breakpoint_disabled = C.Red
293
370
294 # Add a python parser so we can syntax highlight source while
371 # Add a python parser so we can syntax highlight source while
295 # debugging.
372 # debugging.
296 self.parser = PyColorize.Parser(style=color_scheme)
373 self.parser = PyColorize.Parser(style=color_scheme)
297 self.set_colors(color_scheme)
374 self.set_colors(color_scheme)
298
375
299 # Set the prompt - the default prompt is '(Pdb)'
376 # Set the prompt - the default prompt is '(Pdb)'
300 self.prompt = prompt
377 self.prompt = prompt
301 self.skip_hidden = True
378 self.skip_hidden = True
302 self.report_skipped = True
379 self.report_skipped = True
303
380
304 # list of predicates we use to skip frames
381 # list of predicates we use to skip frames
305 self._predicates = self.default_predicates
382 self._predicates = self.default_predicates
383 self._skipping = False
306
384
385 #
307 def set_colors(self, scheme):
386 def set_colors(self, scheme):
308 """Shorthand access to the color table scheme selector method."""
387 """Shorthand access to the color table scheme selector method."""
309 self.color_scheme_table.set_active_scheme(scheme)
388 self.color_scheme_table.set_active_scheme(scheme)
310 self.parser.style = scheme
389 self.parser.style = scheme
311
390
312 def set_trace(self, frame=None):
391 def set_trace(self, frame=None):
313 if frame is None:
392 if frame is None:
314 frame = sys._getframe().f_back
393 frame = sys._getframe().f_back
315 self.initial_frame = frame
394 self.initial_frame = frame
316 return super().set_trace(frame)
395 return super().set_trace(frame)
317
396
318 def _hidden_predicate(self, frame):
397 def _hidden_predicate(self, frame):
319 """
398 """
320 Given a frame return whether it it should be hidden or not by IPython.
399 Given a frame return whether it it should be hidden or not by IPython.
321 """
400 """
322
401
323 if self._predicates["readonly"]:
402 if self._predicates["readonly"]:
324 fname = frame.f_code.co_filename
403 fname = frame.f_code.co_filename
325 # we need to check for file existence and interactively define
404 # we need to check for file existence and interactively define
326 # function would otherwise appear as RO.
405 # function would otherwise appear as RO.
327 if os.path.isfile(fname) and not os.access(fname, os.W_OK):
406 if os.path.isfile(fname) and not os.access(fname, os.W_OK):
328 return True
407 return True
329
408
330 if self._predicates["tbhide"]:
409 if self._predicates["tbhide"]:
331 if frame in (self.curframe, getattr(self, "initial_frame", None)):
410 if frame in (self.curframe, getattr(self, "initial_frame", None)):
332 return False
411 return False
333 else:
412 else:
334 return self._get_frame_locals(frame).get("__tracebackhide__", False)
413 return self._get_frame_locals(frame).get("__tracebackhide__", False)
335
414
336 return False
415 return False
337
416
338 def hidden_frames(self, stack):
417 def hidden_frames(self, stack):
339 """
418 """
340 Given an index in the stack return whether it should be skipped.
419 Given an index in the stack return whether it should be skipped.
341
420
342 This is used in up/down and where to skip frames.
421 This is used in up/down and where to skip frames.
343 """
422 """
344 # The f_locals dictionary is updated from the actual frame
423 # The f_locals dictionary is updated from the actual frame
345 # locals whenever the .f_locals accessor is called, so we
424 # locals whenever the .f_locals accessor is called, so we
346 # avoid calling it here to preserve self.curframe_locals.
425 # avoid calling it here to preserve self.curframe_locals.
347 # Futhermore, there is no good reason to hide the current frame.
426 # Futhermore, there is no good reason to hide the current frame.
348 ip_hide = [self._hidden_predicate(s[0]) for s in stack]
427 ip_hide = [self._hidden_predicate(s[0]) for s in stack]
349 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
428 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
350 if ip_start and self._predicates["ipython_internal"]:
429 if ip_start and self._predicates["ipython_internal"]:
351 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
430 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
352 return ip_hide
431 return ip_hide
353
432
354 def interaction(self, frame, traceback):
433 def interaction(self, frame, traceback):
355 try:
434 try:
356 OldPdb.interaction(self, frame, traceback)
435 OldPdb.interaction(self, frame, traceback)
357 except KeyboardInterrupt:
436 except KeyboardInterrupt:
358 self.stdout.write("\n" + self.shell.get_exception_only())
437 self.stdout.write("\n" + self.shell.get_exception_only())
359
438
360 def precmd(self, line):
439 def precmd(self, line):
361 """Perform useful escapes on the command before it is executed."""
440 """Perform useful escapes on the command before it is executed."""
362
441
363 if line.endswith("??"):
442 if line.endswith("??"):
364 line = "pinfo2 " + line[:-2]
443 line = "pinfo2 " + line[:-2]
365 elif line.endswith("?"):
444 elif line.endswith("?"):
366 line = "pinfo " + line[:-1]
445 line = "pinfo " + line[:-1]
367
446
368 line = super().precmd(line)
447 line = super().precmd(line)
369
448
370 return line
449 return line
371
450
372 def new_do_frame(self, arg):
451 def new_do_frame(self, arg):
373 OldPdb.do_frame(self, arg)
452 OldPdb.do_frame(self, arg)
374
453
375 def new_do_quit(self, arg):
454 def new_do_quit(self, arg):
376
455
377 if hasattr(self, 'old_all_completions'):
456 if hasattr(self, 'old_all_completions'):
378 self.shell.Completer.all_completions = self.old_all_completions
457 self.shell.Completer.all_completions = self.old_all_completions
379
458
380 return OldPdb.do_quit(self, arg)
459 return OldPdb.do_quit(self, arg)
381
460
382 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
461 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
383
462
384 def new_do_restart(self, arg):
463 def new_do_restart(self, arg):
385 """Restart command. In the context of ipython this is exactly the same
464 """Restart command. In the context of ipython this is exactly the same
386 thing as 'quit'."""
465 thing as 'quit'."""
387 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
466 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
388 return self.do_quit(arg)
467 return self.do_quit(arg)
389
468
390 def print_stack_trace(self, context=None):
469 def print_stack_trace(self, context=None):
391 Colors = self.color_scheme_table.active_colors
470 Colors = self.color_scheme_table.active_colors
392 ColorsNormal = Colors.Normal
471 ColorsNormal = Colors.Normal
393 if context is None:
472 if context is None:
394 context = self.context
473 context = self.context
395 try:
474 try:
396 context = int(context)
475 context = int(context)
397 if context <= 0:
476 if context <= 0:
398 raise ValueError("Context must be a positive integer")
477 raise ValueError("Context must be a positive integer")
399 except (TypeError, ValueError) as e:
478 except (TypeError, ValueError) as e:
400 raise ValueError("Context must be a positive integer") from e
479 raise ValueError("Context must be a positive integer") from e
401 try:
480 try:
402 skipped = 0
481 skipped = 0
403 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
482 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
404 if hidden and self.skip_hidden:
483 if hidden and self.skip_hidden:
405 skipped += 1
484 skipped += 1
406 continue
485 continue
407 if skipped:
486 if skipped:
408 print(
487 print(
409 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
488 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
410 )
489 )
411 skipped = 0
490 skipped = 0
412 self.print_stack_entry(frame_lineno, context=context)
491 self.print_stack_entry(frame_lineno, context=context)
413 if skipped:
492 if skipped:
414 print(
493 print(
415 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
494 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
416 )
495 )
417 except KeyboardInterrupt:
496 except KeyboardInterrupt:
418 pass
497 pass
419
498
420 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
499 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
421 context=None):
500 context=None):
422 if context is None:
501 if context is None:
423 context = self.context
502 context = self.context
424 try:
503 try:
425 context = int(context)
504 context = int(context)
426 if context <= 0:
505 if context <= 0:
427 raise ValueError("Context must be a positive integer")
506 raise ValueError("Context must be a positive integer")
428 except (TypeError, ValueError) as e:
507 except (TypeError, ValueError) as e:
429 raise ValueError("Context must be a positive integer") from e
508 raise ValueError("Context must be a positive integer") from e
430 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
509 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
431
510
432 # vds: >>
511 # vds: >>
433 frame, lineno = frame_lineno
512 frame, lineno = frame_lineno
434 filename = frame.f_code.co_filename
513 filename = frame.f_code.co_filename
435 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
514 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
436 # vds: <<
515 # vds: <<
437
516
438 def _get_frame_locals(self, frame):
517 def _get_frame_locals(self, frame):
439 """ "
518 """ "
440 Acessing f_local of current frame reset the namespace, so we want to avoid
519 Acessing f_local of current frame reset the namespace, so we want to avoid
441 that or the following can happend
520 that or the following can happend
442
521
443 ipdb> foo
522 ipdb> foo
444 "old"
523 "old"
445 ipdb> foo = "new"
524 ipdb> foo = "new"
446 ipdb> foo
525 ipdb> foo
447 "new"
526 "new"
448 ipdb> where
527 ipdb> where
449 ipdb> foo
528 ipdb> foo
450 "old"
529 "old"
451
530
452 So if frame is self.current_frame we instead return self.curframe_locals
531 So if frame is self.current_frame we instead return self.curframe_locals
453
532
454 """
533 """
455 if frame is self.curframe:
534 if frame is self.curframe:
456 return self.curframe_locals
535 return self.curframe_locals
457 else:
536 else:
458 return frame.f_locals
537 return frame.f_locals
459
538
460 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
539 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
461 if context is None:
540 if context is None:
462 context = self.context
541 context = self.context
463 try:
542 try:
464 context = int(context)
543 context = int(context)
465 if context <= 0:
544 if context <= 0:
466 print("Context must be a positive integer", file=self.stdout)
545 print("Context must be a positive integer", file=self.stdout)
467 except (TypeError, ValueError):
546 except (TypeError, ValueError):
468 print("Context must be a positive integer", file=self.stdout)
547 print("Context must be a positive integer", file=self.stdout)
469
548
470 import reprlib
549 import reprlib
471
550
472 ret = []
551 ret = []
473
552
474 Colors = self.color_scheme_table.active_colors
553 Colors = self.color_scheme_table.active_colors
475 ColorsNormal = Colors.Normal
554 ColorsNormal = Colors.Normal
476 tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
555 tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
477 tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
556 tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
478 tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
557 tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
479 tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
558 tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
480
559
481 frame, lineno = frame_lineno
560 frame, lineno = frame_lineno
482
561
483 return_value = ''
562 return_value = ''
484 loc_frame = self._get_frame_locals(frame)
563 loc_frame = self._get_frame_locals(frame)
485 if "__return__" in loc_frame:
564 if "__return__" in loc_frame:
486 rv = loc_frame["__return__"]
565 rv = loc_frame["__return__"]
487 # return_value += '->'
566 # return_value += '->'
488 return_value += reprlib.repr(rv) + "\n"
567 return_value += reprlib.repr(rv) + "\n"
489 ret.append(return_value)
568 ret.append(return_value)
490
569
491 #s = filename + '(' + `lineno` + ')'
570 #s = filename + '(' + `lineno` + ')'
492 filename = self.canonic(frame.f_code.co_filename)
571 filename = self.canonic(frame.f_code.co_filename)
493 link = tpl_link % py3compat.cast_unicode(filename)
572 link = tpl_link % py3compat.cast_unicode(filename)
494
573
495 if frame.f_code.co_name:
574 if frame.f_code.co_name:
496 func = frame.f_code.co_name
575 func = frame.f_code.co_name
497 else:
576 else:
498 func = "<lambda>"
577 func = "<lambda>"
499
578
500 call = ""
579 call = ""
501 if func != "?":
580 if func != "?":
502 if "__args__" in loc_frame:
581 if "__args__" in loc_frame:
503 args = reprlib.repr(loc_frame["__args__"])
582 args = reprlib.repr(loc_frame["__args__"])
504 else:
583 else:
505 args = '()'
584 args = '()'
506 call = tpl_call % (func, args)
585 call = tpl_call % (func, args)
507
586
508 # The level info should be generated in the same format pdb uses, to
587 # The level info should be generated in the same format pdb uses, to
509 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
588 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
510 if frame is self.curframe:
589 if frame is self.curframe:
511 ret.append('> ')
590 ret.append('> ')
512 else:
591 else:
513 ret.append(" ")
592 ret.append(" ")
514 ret.append("%s(%s)%s\n" % (link, lineno, call))
593 ret.append("%s(%s)%s\n" % (link, lineno, call))
515
594
516 start = lineno - 1 - context//2
595 start = lineno - 1 - context//2
517 lines = linecache.getlines(filename)
596 lines = linecache.getlines(filename)
518 start = min(start, len(lines) - context)
597 start = min(start, len(lines) - context)
519 start = max(start, 0)
598 start = max(start, 0)
520 lines = lines[start : start + context]
599 lines = lines[start : start + context]
521
600
522 for i, line in enumerate(lines):
601 for i, line in enumerate(lines):
523 show_arrow = start + 1 + i == lineno
602 show_arrow = start + 1 + i == lineno
524 linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
603 linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
525 ret.append(
604 ret.append(
526 self.__format_line(
605 self.__format_line(
527 linetpl, filename, start + 1 + i, line, arrow=show_arrow
606 linetpl, filename, start + 1 + i, line, arrow=show_arrow
528 )
607 )
529 )
608 )
530 return "".join(ret)
609 return "".join(ret)
531
610
532 def __format_line(self, tpl_line, filename, lineno, line, arrow=False):
611 def __format_line(self, tpl_line, filename, lineno, line, arrow=False):
533 bp_mark = ""
612 bp_mark = ""
534 bp_mark_color = ""
613 bp_mark_color = ""
535
614
536 new_line, err = self.parser.format2(line, 'str')
615 new_line, err = self.parser.format2(line, 'str')
537 if not err:
616 if not err:
538 line = new_line
617 line = new_line
539
618
540 bp = None
619 bp = None
541 if lineno in self.get_file_breaks(filename):
620 if lineno in self.get_file_breaks(filename):
542 bps = self.get_breaks(filename, lineno)
621 bps = self.get_breaks(filename, lineno)
543 bp = bps[-1]
622 bp = bps[-1]
544
623
545 if bp:
624 if bp:
546 Colors = self.color_scheme_table.active_colors
625 Colors = self.color_scheme_table.active_colors
547 bp_mark = str(bp.number)
626 bp_mark = str(bp.number)
548 bp_mark_color = Colors.breakpoint_enabled
627 bp_mark_color = Colors.breakpoint_enabled
549 if not bp.enabled:
628 if not bp.enabled:
550 bp_mark_color = Colors.breakpoint_disabled
629 bp_mark_color = Colors.breakpoint_disabled
551
630
552 numbers_width = 7
631 numbers_width = 7
553 if arrow:
632 if arrow:
554 # This is the line with the error
633 # This is the line with the error
555 pad = numbers_width - len(str(lineno)) - len(bp_mark)
634 pad = numbers_width - len(str(lineno)) - len(bp_mark)
556 num = '%s%s' % (make_arrow(pad), str(lineno))
635 num = '%s%s' % (make_arrow(pad), str(lineno))
557 else:
636 else:
558 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
637 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
559
638
560 return tpl_line % (bp_mark_color + bp_mark, num, line)
639 return tpl_line % (bp_mark_color + bp_mark, num, line)
561
640
562 def print_list_lines(self, filename, first, last):
641 def print_list_lines(self, filename, first, last):
563 """The printing (as opposed to the parsing part of a 'list'
642 """The printing (as opposed to the parsing part of a 'list'
564 command."""
643 command."""
565 try:
644 try:
566 Colors = self.color_scheme_table.active_colors
645 Colors = self.color_scheme_table.active_colors
567 ColorsNormal = Colors.Normal
646 ColorsNormal = Colors.Normal
568 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
647 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
569 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
648 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
570 src = []
649 src = []
571 if filename == "<string>" and hasattr(self, "_exec_filename"):
650 if filename == "<string>" and hasattr(self, "_exec_filename"):
572 filename = self._exec_filename
651 filename = self._exec_filename
573
652
574 for lineno in range(first, last+1):
653 for lineno in range(first, last+1):
575 line = linecache.getline(filename, lineno)
654 line = linecache.getline(filename, lineno)
576 if not line:
655 if not line:
577 break
656 break
578
657
579 if lineno == self.curframe.f_lineno:
658 if lineno == self.curframe.f_lineno:
580 line = self.__format_line(
659 line = self.__format_line(
581 tpl_line_em, filename, lineno, line, arrow=True
660 tpl_line_em, filename, lineno, line, arrow=True
582 )
661 )
583 else:
662 else:
584 line = self.__format_line(
663 line = self.__format_line(
585 tpl_line, filename, lineno, line, arrow=False
664 tpl_line, filename, lineno, line, arrow=False
586 )
665 )
587
666
588 src.append(line)
667 src.append(line)
589 self.lineno = lineno
668 self.lineno = lineno
590
669
591 print(''.join(src), file=self.stdout)
670 print(''.join(src), file=self.stdout)
592
671
593 except KeyboardInterrupt:
672 except KeyboardInterrupt:
594 pass
673 pass
595
674
596 def do_skip_predicates(self, args):
675 def do_skip_predicates(self, args):
597 """
676 """
598 Turn on/off individual predicates as to whether a frame should be hidden/skip.
677 Turn on/off individual predicates as to whether a frame should be hidden/skip.
599
678
600 The global option to skip (or not) hidden frames is set with skip_hidden
679 The global option to skip (or not) hidden frames is set with skip_hidden
601
680
602 To change the value of a predicate
681 To change the value of a predicate
603
682
604 skip_predicates key [true|false]
683 skip_predicates key [true|false]
605
684
606 Call without arguments to see the current values.
685 Call without arguments to see the current values.
607
686
608 To permanently change the value of an option add the corresponding
687 To permanently change the value of an option add the corresponding
609 command to your ``~/.pdbrc`` file. If you are programmatically using the
688 command to your ``~/.pdbrc`` file. If you are programmatically using the
610 Pdb instance you can also change the ``default_predicates`` class
689 Pdb instance you can also change the ``default_predicates`` class
611 attribute.
690 attribute.
612 """
691 """
613 if not args.strip():
692 if not args.strip():
614 print("current predicates:")
693 print("current predicates:")
615 for (p, v) in self._predicates.items():
694 for (p, v) in self._predicates.items():
616 print(" ", p, ":", v)
695 print(" ", p, ":", v)
617 return
696 return
618 type_value = args.strip().split(" ")
697 type_value = args.strip().split(" ")
619 if len(type_value) != 2:
698 if len(type_value) != 2:
620 print(
699 print(
621 f"Usage: skip_predicates <type> <value>, with <type> one of {set(self._predicates.keys())}"
700 f"Usage: skip_predicates <type> <value>, with <type> one of {set(self._predicates.keys())}"
622 )
701 )
623 return
702 return
624
703
625 type_, value = type_value
704 type_, value = type_value
626 if type_ not in self._predicates:
705 if type_ not in self._predicates:
627 print(f"{type_!r} not in {set(self._predicates.keys())}")
706 print(f"{type_!r} not in {set(self._predicates.keys())}")
628 return
707 return
629 if value.lower() not in ("true", "yes", "1", "no", "false", "0"):
708 if value.lower() not in ("true", "yes", "1", "no", "false", "0"):
630 print(
709 print(
631 f"{value!r} is invalid - use one of ('true', 'yes', '1', 'no', 'false', '0')"
710 f"{value!r} is invalid - use one of ('true', 'yes', '1', 'no', 'false', '0')"
632 )
711 )
633 return
712 return
634
713
635 self._predicates[type_] = value.lower() in ("true", "yes", "1")
714 self._predicates[type_] = value.lower() in ("true", "yes", "1")
636 if not any(self._predicates.values()):
715 if not any(self._predicates.values()):
637 print(
716 print(
638 "Warning, all predicates set to False, skip_hidden may not have any effects."
717 "Warning, all predicates set to False, skip_hidden may not have any effects."
639 )
718 )
640
719
641 def do_skip_hidden(self, arg):
720 def do_skip_hidden(self, arg):
642 """
721 """
643 Change whether or not we should skip frames with the
722 Change whether or not we should skip frames with the
644 __tracebackhide__ attribute.
723 __tracebackhide__ attribute.
645 """
724 """
646 if not arg.strip():
725 if not arg.strip():
647 print(
726 print(
648 f"skip_hidden = {self.skip_hidden}, use 'yes','no', 'true', or 'false' to change."
727 f"skip_hidden = {self.skip_hidden}, use 'yes','no', 'true', or 'false' to change."
649 )
728 )
650 elif arg.strip().lower() in ("true", "yes"):
729 elif arg.strip().lower() in ("true", "yes"):
651 self.skip_hidden = True
730 self.skip_hidden = True
652 elif arg.strip().lower() in ("false", "no"):
731 elif arg.strip().lower() in ("false", "no"):
653 self.skip_hidden = False
732 self.skip_hidden = False
654 if not any(self._predicates.values()):
733 if not any(self._predicates.values()):
655 print(
734 print(
656 "Warning, all predicates set to False, skip_hidden may not have any effects."
735 "Warning, all predicates set to False, skip_hidden may not have any effects."
657 )
736 )
658
737
659 def do_list(self, arg):
738 def do_list(self, arg):
660 """Print lines of code from the current stack frame
739 """Print lines of code from the current stack frame
661 """
740 """
662 self.lastcmd = 'list'
741 self.lastcmd = 'list'
663 last = None
742 last = None
664 if arg:
743 if arg:
665 try:
744 try:
666 x = eval(arg, {}, {})
745 x = eval(arg, {}, {})
667 if type(x) == type(()):
746 if type(x) == type(()):
668 first, last = x
747 first, last = x
669 first = int(first)
748 first = int(first)
670 last = int(last)
749 last = int(last)
671 if last < first:
750 if last < first:
672 # Assume it's a count
751 # Assume it's a count
673 last = first + last
752 last = first + last
674 else:
753 else:
675 first = max(1, int(x) - 5)
754 first = max(1, int(x) - 5)
676 except:
755 except:
677 print('*** Error in argument:', repr(arg), file=self.stdout)
756 print('*** Error in argument:', repr(arg), file=self.stdout)
678 return
757 return
679 elif self.lineno is None:
758 elif self.lineno is None:
680 first = max(1, self.curframe.f_lineno - 5)
759 first = max(1, self.curframe.f_lineno - 5)
681 else:
760 else:
682 first = self.lineno + 1
761 first = self.lineno + 1
683 if last is None:
762 if last is None:
684 last = first + 10
763 last = first + 10
685 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
764 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
686
765
687 # vds: >>
766 # vds: >>
688 lineno = first
767 lineno = first
689 filename = self.curframe.f_code.co_filename
768 filename = self.curframe.f_code.co_filename
690 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
769 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
691 # vds: <<
770 # vds: <<
692
771
693 do_l = do_list
772 do_l = do_list
694
773
695 def getsourcelines(self, obj):
774 def getsourcelines(self, obj):
696 lines, lineno = inspect.findsource(obj)
775 lines, lineno = inspect.findsource(obj)
697 if inspect.isframe(obj) and obj.f_globals is self._get_frame_locals(obj):
776 if inspect.isframe(obj) and obj.f_globals is self._get_frame_locals(obj):
698 # must be a module frame: do not try to cut a block out of it
777 # must be a module frame: do not try to cut a block out of it
699 return lines, 1
778 return lines, 1
700 elif inspect.ismodule(obj):
779 elif inspect.ismodule(obj):
701 return lines, 1
780 return lines, 1
702 return inspect.getblock(lines[lineno:]), lineno+1
781 return inspect.getblock(lines[lineno:]), lineno+1
703
782
704 def do_longlist(self, arg):
783 def do_longlist(self, arg):
705 """Print lines of code from the current stack frame.
784 """Print lines of code from the current stack frame.
706
785
707 Shows more lines than 'list' does.
786 Shows more lines than 'list' does.
708 """
787 """
709 self.lastcmd = 'longlist'
788 self.lastcmd = 'longlist'
710 try:
789 try:
711 lines, lineno = self.getsourcelines(self.curframe)
790 lines, lineno = self.getsourcelines(self.curframe)
712 except OSError as err:
791 except OSError as err:
713 self.error(err)
792 self.error(err)
714 return
793 return
715 last = lineno + len(lines)
794 last = lineno + len(lines)
716 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
795 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
717 do_ll = do_longlist
796 do_ll = do_longlist
718
797
719 def do_debug(self, arg):
798 def do_debug(self, arg):
720 """debug code
799 """debug code
721 Enter a recursive debugger that steps through the code
800 Enter a recursive debugger that steps through the code
722 argument (which is an arbitrary expression or statement to be
801 argument (which is an arbitrary expression or statement to be
723 executed in the current environment).
802 executed in the current environment).
724 """
803 """
725 trace_function = sys.gettrace()
804 trace_function = sys.gettrace()
726 sys.settrace(None)
805 sys.settrace(None)
727 globals = self.curframe.f_globals
806 globals = self.curframe.f_globals
728 locals = self.curframe_locals
807 locals = self.curframe_locals
729 p = self.__class__(completekey=self.completekey,
808 p = self.__class__(completekey=self.completekey,
730 stdin=self.stdin, stdout=self.stdout)
809 stdin=self.stdin, stdout=self.stdout)
731 p.use_rawinput = self.use_rawinput
810 p.use_rawinput = self.use_rawinput
732 p.prompt = "(%s) " % self.prompt.strip()
811 p.prompt = "(%s) " % self.prompt.strip()
733 self.message("ENTERING RECURSIVE DEBUGGER")
812 self.message("ENTERING RECURSIVE DEBUGGER")
734 sys.call_tracing(p.run, (arg, globals, locals))
813 sys.call_tracing(p.run, (arg, globals, locals))
735 self.message("LEAVING RECURSIVE DEBUGGER")
814 self.message("LEAVING RECURSIVE DEBUGGER")
736 sys.settrace(trace_function)
815 sys.settrace(trace_function)
737 self.lastcmd = p.lastcmd
816 self.lastcmd = p.lastcmd
738
817
739 def do_pdef(self, arg):
818 def do_pdef(self, arg):
740 """Print the call signature for any callable object.
819 """Print the call signature for any callable object.
741
820
742 The debugger interface to %pdef"""
821 The debugger interface to %pdef"""
743 namespaces = [
822 namespaces = [
744 ("Locals", self.curframe_locals),
823 ("Locals", self.curframe_locals),
745 ("Globals", self.curframe.f_globals),
824 ("Globals", self.curframe.f_globals),
746 ]
825 ]
747 self.shell.find_line_magic("pdef")(arg, namespaces=namespaces)
826 self.shell.find_line_magic("pdef")(arg, namespaces=namespaces)
748
827
749 def do_pdoc(self, arg):
828 def do_pdoc(self, arg):
750 """Print the docstring for an object.
829 """Print the docstring for an object.
751
830
752 The debugger interface to %pdoc."""
831 The debugger interface to %pdoc."""
753 namespaces = [
832 namespaces = [
754 ("Locals", self.curframe_locals),
833 ("Locals", self.curframe_locals),
755 ("Globals", self.curframe.f_globals),
834 ("Globals", self.curframe.f_globals),
756 ]
835 ]
757 self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces)
836 self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces)
758
837
759 def do_pfile(self, arg):
838 def do_pfile(self, arg):
760 """Print (or run through pager) the file where an object is defined.
839 """Print (or run through pager) the file where an object is defined.
761
840
762 The debugger interface to %pfile.
841 The debugger interface to %pfile.
763 """
842 """
764 namespaces = [
843 namespaces = [
765 ("Locals", self.curframe_locals),
844 ("Locals", self.curframe_locals),
766 ("Globals", self.curframe.f_globals),
845 ("Globals", self.curframe.f_globals),
767 ]
846 ]
768 self.shell.find_line_magic("pfile")(arg, namespaces=namespaces)
847 self.shell.find_line_magic("pfile")(arg, namespaces=namespaces)
769
848
770 def do_pinfo(self, arg):
849 def do_pinfo(self, arg):
771 """Provide detailed information about an object.
850 """Provide detailed information about an object.
772
851
773 The debugger interface to %pinfo, i.e., obj?."""
852 The debugger interface to %pinfo, i.e., obj?."""
774 namespaces = [
853 namespaces = [
775 ("Locals", self.curframe_locals),
854 ("Locals", self.curframe_locals),
776 ("Globals", self.curframe.f_globals),
855 ("Globals", self.curframe.f_globals),
777 ]
856 ]
778 self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces)
857 self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces)
779
858
780 def do_pinfo2(self, arg):
859 def do_pinfo2(self, arg):
781 """Provide extra detailed information about an object.
860 """Provide extra detailed information about an object.
782
861
783 The debugger interface to %pinfo2, i.e., obj??."""
862 The debugger interface to %pinfo2, i.e., obj??."""
784 namespaces = [
863 namespaces = [
785 ("Locals", self.curframe_locals),
864 ("Locals", self.curframe_locals),
786 ("Globals", self.curframe.f_globals),
865 ("Globals", self.curframe.f_globals),
787 ]
866 ]
788 self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
867 self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
789
868
790 def do_psource(self, arg):
869 def do_psource(self, arg):
791 """Print (or run through pager) the source code for an object."""
870 """Print (or run through pager) the source code for an object."""
792 namespaces = [
871 namespaces = [
793 ("Locals", self.curframe_locals),
872 ("Locals", self.curframe_locals),
794 ("Globals", self.curframe.f_globals),
873 ("Globals", self.curframe.f_globals),
795 ]
874 ]
796 self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
875 self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
797
876
798 def do_where(self, arg):
877 def do_where(self, arg):
799 """w(here)
878 """w(here)
800 Print a stack trace, with the most recent frame at the bottom.
879 Print a stack trace, with the most recent frame at the bottom.
801 An arrow indicates the "current frame", which determines the
880 An arrow indicates the "current frame", which determines the
802 context of most commands. 'bt' is an alias for this command.
881 context of most commands. 'bt' is an alias for this command.
803
882
804 Take a number as argument as an (optional) number of context line to
883 Take a number as argument as an (optional) number of context line to
805 print"""
884 print"""
806 if arg:
885 if arg:
807 try:
886 try:
808 context = int(arg)
887 context = int(arg)
809 except ValueError as err:
888 except ValueError as err:
810 self.error(err)
889 self.error(err)
811 return
890 return
812 self.print_stack_trace(context)
891 self.print_stack_trace(context)
813 else:
892 else:
814 self.print_stack_trace()
893 self.print_stack_trace()
815
894
816 do_w = do_where
895 do_w = do_where
817
896
897 def break_anywhere(self, frame):
898 """
899
900 _stop_in_decorator_internals is overly restrictive, as we may still want
901 to trace function calls, so we need to also update break_anywhere so
902 that is we don't `stop_here`, because of debugger skip, we may still
903 stop at any point inside the function
904
905 """
906 if self._predicates["debuggerskip"]:
907 if DEBUGGERSKIP in frame.f_code.co_varnames:
908 return True
909 if frame.f_back and self._get_frame_locals(frame.f_back).get(DEBUGGERSKIP):
910 return True
911 return super().break_anywhere(frame)
912
913 @skip_doctest
914 def _is_in_decorator_internal_and_should_skip(self, frame):
915 """
916 Utility to tell us whether we are in a decorator internal and should stop.
917
918
919
920 """
921
922 # if we are disable don't skip
923 if not self._predicates["debuggerskip"]:
924 return False
925
926 # if frame is tagged, skip by default.
927 if DEBUGGERSKIP in frame.f_code.co_varnames:
928 return True
929
930 # if parent frame value set to True skip as well.
931 if frame.f_back and self._get_frame_locals(frame.f_back).get(DEBUGGERSKIP):
932 return True
933
934 return False
935
818 def stop_here(self, frame):
936 def stop_here(self, frame):
937
938 if self._is_in_decorator_internal_and_should_skip(frame) is True:
939 return False
940
819 hidden = False
941 hidden = False
820 if self.skip_hidden:
942 if self.skip_hidden:
821 hidden = self._hidden_predicate(frame)
943 hidden = self._hidden_predicate(frame)
822 if hidden:
944 if hidden:
823 if self.report_skipped:
945 if self.report_skipped:
824 Colors = self.color_scheme_table.active_colors
946 Colors = self.color_scheme_table.active_colors
825 ColorsNormal = Colors.Normal
947 ColorsNormal = Colors.Normal
826 print(
948 print(
827 f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n"
949 f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n"
828 )
950 )
829 return super().stop_here(frame)
951 return super().stop_here(frame)
830
952
831 def do_up(self, arg):
953 def do_up(self, arg):
832 """u(p) [count]
954 """u(p) [count]
833 Move the current frame count (default one) levels up in the
955 Move the current frame count (default one) levels up in the
834 stack trace (to an older frame).
956 stack trace (to an older frame).
835
957
836 Will skip hidden frames.
958 Will skip hidden frames.
837 """
959 """
838 # modified version of upstream that skips
960 # modified version of upstream that skips
839 # frames with __tracebackhide__
961 # frames with __tracebackhide__
840 if self.curindex == 0:
962 if self.curindex == 0:
841 self.error("Oldest frame")
963 self.error("Oldest frame")
842 return
964 return
843 try:
965 try:
844 count = int(arg or 1)
966 count = int(arg or 1)
845 except ValueError:
967 except ValueError:
846 self.error("Invalid frame count (%s)" % arg)
968 self.error("Invalid frame count (%s)" % arg)
847 return
969 return
848 skipped = 0
970 skipped = 0
849 if count < 0:
971 if count < 0:
850 _newframe = 0
972 _newframe = 0
851 else:
973 else:
852 counter = 0
974 counter = 0
853 hidden_frames = self.hidden_frames(self.stack)
975 hidden_frames = self.hidden_frames(self.stack)
854 for i in range(self.curindex - 1, -1, -1):
976 for i in range(self.curindex - 1, -1, -1):
855 if hidden_frames[i] and self.skip_hidden:
977 if hidden_frames[i] and self.skip_hidden:
856 skipped += 1
978 skipped += 1
857 continue
979 continue
858 counter += 1
980 counter += 1
859 if counter >= count:
981 if counter >= count:
860 break
982 break
861 else:
983 else:
862 # if no break occured.
984 # if no break occured.
863 self.error(
985 self.error(
864 "all frames above hidden, use `skip_hidden False` to get get into those."
986 "all frames above hidden, use `skip_hidden False` to get get into those."
865 )
987 )
866 return
988 return
867
989
868 Colors = self.color_scheme_table.active_colors
990 Colors = self.color_scheme_table.active_colors
869 ColorsNormal = Colors.Normal
991 ColorsNormal = Colors.Normal
870 _newframe = i
992 _newframe = i
871 self._select_frame(_newframe)
993 self._select_frame(_newframe)
872 if skipped:
994 if skipped:
873 print(
995 print(
874 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
996 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
875 )
997 )
876
998
877 def do_down(self, arg):
999 def do_down(self, arg):
878 """d(own) [count]
1000 """d(own) [count]
879 Move the current frame count (default one) levels down in the
1001 Move the current frame count (default one) levels down in the
880 stack trace (to a newer frame).
1002 stack trace (to a newer frame).
881
1003
882 Will skip hidden frames.
1004 Will skip hidden frames.
883 """
1005 """
884 if self.curindex + 1 == len(self.stack):
1006 if self.curindex + 1 == len(self.stack):
885 self.error("Newest frame")
1007 self.error("Newest frame")
886 return
1008 return
887 try:
1009 try:
888 count = int(arg or 1)
1010 count = int(arg or 1)
889 except ValueError:
1011 except ValueError:
890 self.error("Invalid frame count (%s)" % arg)
1012 self.error("Invalid frame count (%s)" % arg)
891 return
1013 return
892 if count < 0:
1014 if count < 0:
893 _newframe = len(self.stack) - 1
1015 _newframe = len(self.stack) - 1
894 else:
1016 else:
895 counter = 0
1017 counter = 0
896 skipped = 0
1018 skipped = 0
897 hidden_frames = self.hidden_frames(self.stack)
1019 hidden_frames = self.hidden_frames(self.stack)
898 for i in range(self.curindex + 1, len(self.stack)):
1020 for i in range(self.curindex + 1, len(self.stack)):
899 if hidden_frames[i] and self.skip_hidden:
1021 if hidden_frames[i] and self.skip_hidden:
900 skipped += 1
1022 skipped += 1
901 continue
1023 continue
902 counter += 1
1024 counter += 1
903 if counter >= count:
1025 if counter >= count:
904 break
1026 break
905 else:
1027 else:
906 self.error(
1028 self.error(
907 "all frames bellow hidden, use `skip_hidden False` to get get into those."
1029 "all frames bellow hidden, use `skip_hidden False` to get get into those."
908 )
1030 )
909 return
1031 return
910
1032
911 Colors = self.color_scheme_table.active_colors
1033 Colors = self.color_scheme_table.active_colors
912 ColorsNormal = Colors.Normal
1034 ColorsNormal = Colors.Normal
913 if skipped:
1035 if skipped:
914 print(
1036 print(
915 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
1037 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
916 )
1038 )
917 _newframe = i
1039 _newframe = i
918
1040
919 self._select_frame(_newframe)
1041 self._select_frame(_newframe)
920
1042
921 do_d = do_down
1043 do_d = do_down
922 do_u = do_up
1044 do_u = do_up
923
1045
924 def do_context(self, context):
1046 def do_context(self, context):
925 """context number_of_lines
1047 """context number_of_lines
926 Set the number of lines of source code to show when displaying
1048 Set the number of lines of source code to show when displaying
927 stacktrace information.
1049 stacktrace information.
928 """
1050 """
929 try:
1051 try:
930 new_context = int(context)
1052 new_context = int(context)
931 if new_context <= 0:
1053 if new_context <= 0:
932 raise ValueError()
1054 raise ValueError()
933 self.context = new_context
1055 self.context = new_context
934 except ValueError:
1056 except ValueError:
935 self.error("The 'context' command requires a positive integer argument.")
1057 self.error("The 'context' command requires a positive integer argument.")
936
1058
937
1059
938 class InterruptiblePdb(Pdb):
1060 class InterruptiblePdb(Pdb):
939 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
1061 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
940
1062
941 def cmdloop(self):
1063 def cmdloop(self, intro=None):
942 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
1064 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
943 try:
1065 try:
944 return OldPdb.cmdloop(self)
1066 return OldPdb.cmdloop(self, intro=intro)
945 except KeyboardInterrupt:
1067 except KeyboardInterrupt:
946 self.stop_here = lambda frame: False
1068 self.stop_here = lambda frame: False
947 self.do_quit("")
1069 self.do_quit("")
948 sys.settrace(None)
1070 sys.settrace(None)
949 self.quitting = False
1071 self.quitting = False
950 raise
1072 raise
951
1073
952 def _cmdloop(self):
1074 def _cmdloop(self):
953 while True:
1075 while True:
954 try:
1076 try:
955 # keyboard interrupts allow for an easy way to cancel
1077 # keyboard interrupts allow for an easy way to cancel
956 # the current command, so allow them during interactive input
1078 # the current command, so allow them during interactive input
957 self.allow_kbdint = True
1079 self.allow_kbdint = True
958 self.cmdloop()
1080 self.cmdloop()
959 self.allow_kbdint = False
1081 self.allow_kbdint = False
960 break
1082 break
961 except KeyboardInterrupt:
1083 except KeyboardInterrupt:
962 self.message('--KeyboardInterrupt--')
1084 self.message('--KeyboardInterrupt--')
963 raise
1085 raise
964
1086
965
1087
966 def set_trace(frame=None):
1088 def set_trace(frame=None):
967 """
1089 """
968 Start debugging from `frame`.
1090 Start debugging from `frame`.
969
1091
970 If frame is not specified, debugging starts from caller's frame.
1092 If frame is not specified, debugging starts from caller's frame.
971 """
1093 """
972 Pdb().set_trace(frame or sys._getframe().f_back)
1094 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,390 +1,502 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 signal
10 import signal
11 import subprocess
11 import subprocess
12 import sys
12 import sys
13 import time
13 import time
14 import warnings
14 import warnings
15 from subprocess import PIPE, CalledProcessError, check_output
15 from subprocess import PIPE, CalledProcessError, check_output
16 from tempfile import NamedTemporaryFile
16 from tempfile import NamedTemporaryFile
17 from textwrap import dedent
17 from textwrap import dedent
18 from unittest.mock import patch
18 from unittest.mock import patch
19
19
20 import nose.tools as nt
20 import nose.tools as nt
21
21
22 from IPython.core import debugger
22 from IPython.core import debugger
23 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
23 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
24 from IPython.testing.decorators import skip_win32
24 from IPython.testing.decorators import skip_win32
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Helper classes, from CPython's Pdb test suite
27 # Helper classes, from CPython's Pdb test suite
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class _FakeInput(object):
30 class _FakeInput(object):
31 """
31 """
32 A fake input stream for pdb's interactive debugger. Whenever a
32 A fake input stream for pdb's interactive debugger. Whenever a
33 line is read, print it (to simulate the user typing it), and then
33 line is read, print it (to simulate the user typing it), and then
34 return it. The set of lines to return is specified in the
34 return it. The set of lines to return is specified in the
35 constructor; they should not have trailing newlines.
35 constructor; they should not have trailing newlines.
36 """
36 """
37 def __init__(self, lines):
37 def __init__(self, lines):
38 self.lines = iter(lines)
38 self.lines = iter(lines)
39
39
40 def readline(self):
40 def readline(self):
41 line = next(self.lines)
41 line = next(self.lines)
42 print(line)
42 print(line)
43 return line+'\n'
43 return line+'\n'
44
44
45 class PdbTestInput(object):
45 class PdbTestInput(object):
46 """Context manager that makes testing Pdb in doctests easier."""
46 """Context manager that makes testing Pdb in doctests easier."""
47
47
48 def __init__(self, input):
48 def __init__(self, input):
49 self.input = input
49 self.input = input
50
50
51 def __enter__(self):
51 def __enter__(self):
52 self.real_stdin = sys.stdin
52 self.real_stdin = sys.stdin
53 sys.stdin = _FakeInput(self.input)
53 sys.stdin = _FakeInput(self.input)
54
54
55 def __exit__(self, *exc):
55 def __exit__(self, *exc):
56 sys.stdin = self.real_stdin
56 sys.stdin = self.real_stdin
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Tests
59 # Tests
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62 def test_longer_repr():
62 def test_longer_repr():
63 from reprlib import repr as trepr
63 from reprlib import repr as trepr
64
64
65 a = '1234567890'* 7
65 a = '1234567890'* 7
66 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
66 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
67 a_trunc = "'123456789012...8901234567890'"
67 a_trunc = "'123456789012...8901234567890'"
68 nt.assert_equal(trepr(a), a_trunc)
68 nt.assert_equal(trepr(a), a_trunc)
69 # The creation of our tracer modifies the repr module's repr function
69 # The creation of our tracer modifies the repr module's repr function
70 # in-place, since that global is used directly by the stdlib's pdb module.
70 # in-place, since that global is used directly by the stdlib's pdb module.
71 with warnings.catch_warnings():
71 with warnings.catch_warnings():
72 warnings.simplefilter('ignore', DeprecationWarning)
72 warnings.simplefilter('ignore', DeprecationWarning)
73 debugger.Tracer()
73 debugger.Tracer()
74 nt.assert_equal(trepr(a), ar)
74 nt.assert_equal(trepr(a), ar)
75
75
76 def test_ipdb_magics():
76 def test_ipdb_magics():
77 '''Test calling some IPython magics from ipdb.
77 '''Test calling some IPython magics from ipdb.
78
78
79 First, set up some test functions and classes which we can inspect.
79 First, set up some test functions and classes which we can inspect.
80
80
81 >>> class ExampleClass(object):
81 >>> class ExampleClass(object):
82 ... """Docstring for ExampleClass."""
82 ... """Docstring for ExampleClass."""
83 ... def __init__(self):
83 ... def __init__(self):
84 ... """Docstring for ExampleClass.__init__"""
84 ... """Docstring for ExampleClass.__init__"""
85 ... pass
85 ... pass
86 ... def __str__(self):
86 ... def __str__(self):
87 ... return "ExampleClass()"
87 ... return "ExampleClass()"
88
88
89 >>> def example_function(x, y, z="hello"):
89 >>> def example_function(x, y, z="hello"):
90 ... """Docstring for example_function."""
90 ... """Docstring for example_function."""
91 ... pass
91 ... pass
92
92
93 >>> old_trace = sys.gettrace()
93 >>> old_trace = sys.gettrace()
94
94
95 Create a function which triggers ipdb.
95 Create a function which triggers ipdb.
96
96
97 >>> def trigger_ipdb():
97 >>> def trigger_ipdb():
98 ... a = ExampleClass()
98 ... a = ExampleClass()
99 ... debugger.Pdb().set_trace()
99 ... debugger.Pdb().set_trace()
100
100
101 >>> with PdbTestInput([
101 >>> with PdbTestInput([
102 ... 'pdef example_function',
102 ... 'pdef example_function',
103 ... 'pdoc ExampleClass',
103 ... 'pdoc ExampleClass',
104 ... 'up',
104 ... 'up',
105 ... 'down',
105 ... 'down',
106 ... 'list',
106 ... 'list',
107 ... 'pinfo a',
107 ... 'pinfo a',
108 ... 'll',
108 ... 'll',
109 ... 'continue',
109 ... 'continue',
110 ... ]):
110 ... ]):
111 ... trigger_ipdb()
111 ... trigger_ipdb()
112 --Return--
112 --Return--
113 None
113 None
114 > <doctest ...>(3)trigger_ipdb()
114 > <doctest ...>(3)trigger_ipdb()
115 1 def trigger_ipdb():
115 1 def trigger_ipdb():
116 2 a = ExampleClass()
116 2 a = ExampleClass()
117 ----> 3 debugger.Pdb().set_trace()
117 ----> 3 debugger.Pdb().set_trace()
118 <BLANKLINE>
118 <BLANKLINE>
119 ipdb> pdef example_function
119 ipdb> pdef example_function
120 example_function(x, y, z='hello')
120 example_function(x, y, z='hello')
121 ipdb> pdoc ExampleClass
121 ipdb> pdoc ExampleClass
122 Class docstring:
122 Class docstring:
123 Docstring for ExampleClass.
123 Docstring for ExampleClass.
124 Init docstring:
124 Init docstring:
125 Docstring for ExampleClass.__init__
125 Docstring for ExampleClass.__init__
126 ipdb> up
126 ipdb> up
127 > <doctest ...>(11)<module>()
127 > <doctest ...>(11)<module>()
128 7 'pinfo a',
128 7 'pinfo a',
129 8 'll',
129 8 'll',
130 9 'continue',
130 9 'continue',
131 10 ]):
131 10 ]):
132 ---> 11 trigger_ipdb()
132 ---> 11 trigger_ipdb()
133 <BLANKLINE>
133 <BLANKLINE>
134 ipdb> down
134 ipdb> down
135 None
135 None
136 > <doctest ...>(3)trigger_ipdb()
136 > <doctest ...>(3)trigger_ipdb()
137 1 def trigger_ipdb():
137 1 def trigger_ipdb():
138 2 a = ExampleClass()
138 2 a = ExampleClass()
139 ----> 3 debugger.Pdb().set_trace()
139 ----> 3 debugger.Pdb().set_trace()
140 <BLANKLINE>
140 <BLANKLINE>
141 ipdb> list
141 ipdb> list
142 1 def trigger_ipdb():
142 1 def trigger_ipdb():
143 2 a = ExampleClass()
143 2 a = ExampleClass()
144 ----> 3 debugger.Pdb().set_trace()
144 ----> 3 debugger.Pdb().set_trace()
145 <BLANKLINE>
145 <BLANKLINE>
146 ipdb> pinfo a
146 ipdb> pinfo a
147 Type: ExampleClass
147 Type: ExampleClass
148 String form: ExampleClass()
148 String form: ExampleClass()
149 Namespace: Local...
149 Namespace: Local...
150 Docstring: Docstring for ExampleClass.
150 Docstring: Docstring for ExampleClass.
151 Init docstring: Docstring for ExampleClass.__init__
151 Init docstring: Docstring for ExampleClass.__init__
152 ipdb> ll
152 ipdb> ll
153 1 def trigger_ipdb():
153 1 def trigger_ipdb():
154 2 a = ExampleClass()
154 2 a = ExampleClass()
155 ----> 3 debugger.Pdb().set_trace()
155 ----> 3 debugger.Pdb().set_trace()
156 <BLANKLINE>
156 <BLANKLINE>
157 ipdb> continue
157 ipdb> continue
158
158
159 Restore previous trace function, e.g. for coverage.py
159 Restore previous trace function, e.g. for coverage.py
160
160
161 >>> sys.settrace(old_trace)
161 >>> sys.settrace(old_trace)
162 '''
162 '''
163
163
164 def test_ipdb_magics2():
164 def test_ipdb_magics2():
165 '''Test ipdb with a very short function.
165 '''Test ipdb with a very short function.
166
166
167 >>> old_trace = sys.gettrace()
167 >>> old_trace = sys.gettrace()
168
168
169 >>> def bar():
169 >>> def bar():
170 ... pass
170 ... pass
171
171
172 Run ipdb.
172 Run ipdb.
173
173
174 >>> with PdbTestInput([
174 >>> with PdbTestInput([
175 ... 'continue',
175 ... 'continue',
176 ... ]):
176 ... ]):
177 ... debugger.Pdb().runcall(bar)
177 ... debugger.Pdb().runcall(bar)
178 > <doctest ...>(2)bar()
178 > <doctest ...>(2)bar()
179 1 def bar():
179 1 def bar():
180 ----> 2 pass
180 ----> 2 pass
181 <BLANKLINE>
181 <BLANKLINE>
182 ipdb> continue
182 ipdb> continue
183
183
184 Restore previous trace function, e.g. for coverage.py
184 Restore previous trace function, e.g. for coverage.py
185
185
186 >>> sys.settrace(old_trace)
186 >>> sys.settrace(old_trace)
187 '''
187 '''
188
188
189 def can_quit():
189 def can_quit():
190 '''Test that quit work in ipydb
190 '''Test that quit work in ipydb
191
191
192 >>> old_trace = sys.gettrace()
192 >>> old_trace = sys.gettrace()
193
193
194 >>> def bar():
194 >>> def bar():
195 ... pass
195 ... pass
196
196
197 >>> with PdbTestInput([
197 >>> with PdbTestInput([
198 ... 'quit',
198 ... 'quit',
199 ... ]):
199 ... ]):
200 ... debugger.Pdb().runcall(bar)
200 ... debugger.Pdb().runcall(bar)
201 > <doctest ...>(2)bar()
201 > <doctest ...>(2)bar()
202 1 def bar():
202 1 def bar():
203 ----> 2 pass
203 ----> 2 pass
204 <BLANKLINE>
204 <BLANKLINE>
205 ipdb> quit
205 ipdb> quit
206
206
207 Restore previous trace function, e.g. for coverage.py
207 Restore previous trace function, e.g. for coverage.py
208
208
209 >>> sys.settrace(old_trace)
209 >>> sys.settrace(old_trace)
210 '''
210 '''
211
211
212
212
213 def can_exit():
213 def can_exit():
214 '''Test that quit work in ipydb
214 '''Test that quit work in ipydb
215
215
216 >>> old_trace = sys.gettrace()
216 >>> old_trace = sys.gettrace()
217
217
218 >>> def bar():
218 >>> def bar():
219 ... pass
219 ... pass
220
220
221 >>> with PdbTestInput([
221 >>> with PdbTestInput([
222 ... 'exit',
222 ... 'exit',
223 ... ]):
223 ... ]):
224 ... debugger.Pdb().runcall(bar)
224 ... debugger.Pdb().runcall(bar)
225 > <doctest ...>(2)bar()
225 > <doctest ...>(2)bar()
226 1 def bar():
226 1 def bar():
227 ----> 2 pass
227 ----> 2 pass
228 <BLANKLINE>
228 <BLANKLINE>
229 ipdb> exit
229 ipdb> exit
230
230
231 Restore previous trace function, e.g. for coverage.py
231 Restore previous trace function, e.g. for coverage.py
232
232
233 >>> sys.settrace(old_trace)
233 >>> sys.settrace(old_trace)
234 '''
234 '''
235
235
236
236
237 def test_interruptible_core_debugger():
237 def test_interruptible_core_debugger():
238 """The debugger can be interrupted.
238 """The debugger can be interrupted.
239
239
240 The presumption is there is some mechanism that causes a KeyboardInterrupt
240 The presumption is there is some mechanism that causes a KeyboardInterrupt
241 (this is implemented in ipykernel). We want to ensure the
241 (this is implemented in ipykernel). We want to ensure the
242 KeyboardInterrupt cause debugging to cease.
242 KeyboardInterrupt cause debugging to cease.
243 """
243 """
244 def raising_input(msg="", called=[0]):
244 def raising_input(msg="", called=[0]):
245 called[0] += 1
245 called[0] += 1
246 if called[0] == 1:
246 if called[0] == 1:
247 raise KeyboardInterrupt()
247 raise KeyboardInterrupt()
248 else:
248 else:
249 raise AssertionError("input() should only be called once!")
249 raise AssertionError("input() should only be called once!")
250
250
251 with patch.object(builtins, "input", raising_input):
251 with patch.object(builtins, "input", raising_input):
252 debugger.InterruptiblePdb().set_trace()
252 debugger.InterruptiblePdb().set_trace()
253 # The way this test will fail is by set_trace() never exiting,
253 # The way this test will fail is by set_trace() never exiting,
254 # resulting in a timeout by the test runner. The alternative
254 # resulting in a timeout by the test runner. The alternative
255 # implementation would involve a subprocess, but that adds issues with
255 # implementation would involve a subprocess, but that adds issues with
256 # interrupting subprocesses that are rather complex, so it's simpler
256 # interrupting subprocesses that are rather complex, so it's simpler
257 # just to do it this way.
257 # just to do it this way.
258
258
259 @skip_win32
259 @skip_win32
260 def test_xmode_skip():
260 def test_xmode_skip():
261 """that xmode skip frames
261 """that xmode skip frames
262
262
263 Not as a doctest as pytest does not run doctests.
263 Not as a doctest as pytest does not run doctests.
264 """
264 """
265 import pexpect
265 import pexpect
266 env = os.environ.copy()
266 env = os.environ.copy()
267 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
267 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
268
268
269 child = pexpect.spawn(
269 child = pexpect.spawn(
270 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
270 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
271 )
271 )
272 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
272 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
273
273
274 child.expect("IPython")
274 child.expect("IPython")
275 child.expect("\n")
275 child.expect("\n")
276 child.expect_exact("In [1]")
276 child.expect_exact("In [1]")
277
277
278 block = dedent(
278 block = dedent(
279 """
279 """
280 def f():
280 def f():
281 __tracebackhide__ = True
281 __tracebackhide__ = True
282 g()
282 g()
283
283
284 def g():
284 def g():
285 raise ValueError
285 raise ValueError
286
286
287 f()
287 f()
288 """
288 """
289 )
289 )
290
290
291 for line in block.splitlines():
291 for line in block.splitlines():
292 child.sendline(line)
292 child.sendline(line)
293 child.expect_exact(line)
293 child.expect_exact(line)
294 child.expect_exact("skipping")
294 child.expect_exact("skipping")
295
295
296 block = dedent(
296 block = dedent(
297 """
297 """
298 def f():
298 def f():
299 __tracebackhide__ = True
299 __tracebackhide__ = True
300 g()
300 g()
301
301
302 def g():
302 def g():
303 from IPython.core.debugger import set_trace
303 from IPython.core.debugger import set_trace
304 set_trace()
304 set_trace()
305
305
306 f()
306 f()
307 """
307 """
308 )
308 )
309
309
310 for line in block.splitlines():
310 for line in block.splitlines():
311 child.sendline(line)
311 child.sendline(line)
312 child.expect_exact(line)
312 child.expect_exact(line)
313
313
314 child.expect("ipdb>")
314 child.expect("ipdb>")
315 child.sendline("w")
315 child.sendline("w")
316 child.expect("hidden")
316 child.expect("hidden")
317 child.expect("ipdb>")
317 child.expect("ipdb>")
318 child.sendline("skip_hidden false")
318 child.sendline("skip_hidden false")
319 child.sendline("w")
319 child.sendline("w")
320 child.expect("__traceba")
320 child.expect("__traceba")
321 child.expect("ipdb>")
321 child.expect("ipdb>")
322
322
323 child.close()
323 child.close()
324
324
325
325
326 skip_decorators_blocks = (
327 """
328 def helper_1():
329 pass # should not stop here
330 """,
331 """
332 def helper_2():
333 pass # should not stop here
334 """,
335 """
336 def pdb_skipped_decorator(function):
337 def wrapped_fn(*args, **kwargs):
338 __debuggerskip__ = True
339 helper_1()
340 __debuggerskip__ = False
341 result = function(*args, **kwargs)
342 __debuggerskip__ = True
343 helper_2()
344 return result
345 return wrapped_fn
346 """,
347 """
348 @pdb_skipped_decorator
349 def bar(x, y):
350 return x * y
351 """,
352 """import IPython.terminal.debugger as ipdb""",
353 """
354 def f():
355 ipdb.set_trace()
356 bar(3, 4)
357 """,
358 """
359 f()
360 """,
361 )
362
363
364 def _decorator_skip_setup():
365 import pexpect
366
367 env = os.environ.copy()
368 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
369
370 child = pexpect.spawn(
371 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
372 )
373 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
374
375 child.expect("IPython")
376 child.expect("\n")
377
378 dedented_blocks = [dedent(b).strip() for b in skip_decorators_blocks]
379 in_prompt_number = 1
380 for cblock in dedented_blocks:
381 child.expect_exact(f"In [{in_prompt_number}]:")
382 in_prompt_number += 1
383 for line in cblock.splitlines():
384 child.sendline(line)
385 child.expect_exact(line)
386 child.sendline("")
387 return child
388
389
390 @skip_win32
391 def test_decorator_skip():
392 """test that decorator frames can be skipped."""
393
394 child = _decorator_skip_setup()
395
396 child.expect_exact("3 bar(3, 4)")
397 child.expect("ipdb>")
398
399 child.expect("ipdb>")
400 child.sendline("step")
401 child.expect_exact("step")
402
403 child.expect_exact("1 @pdb_skipped_decorator")
404
405 child.sendline("s")
406 child.expect_exact("return x * y")
407
408 child.close()
409
410
411 @skip_win32
412 def test_decorator_skip_disabled():
413 """test that decorator frame skipping can be disabled"""
414
415 child = _decorator_skip_setup()
416
417 child.expect_exact("3 bar(3, 4)")
418
419 for input_, expected in [
420 ("skip_predicates debuggerskip False", ""),
421 ("skip_predicates", "debuggerskip : False"),
422 ("step", "---> 2 def wrapped_fn"),
423 ("step", "----> 3 __debuggerskip__"),
424 ("step", "----> 4 helper_1()"),
425 ("step", "---> 1 def helper_1():"),
426 ("next", "----> 2 pass"),
427 ("next", "--Return--"),
428 ("next", "----> 5 __debuggerskip__ = False"),
429 ]:
430 child.expect("ipdb>")
431 child.sendline(input_)
432 child.expect_exact(input_)
433 child.expect_exact(expected)
434
435 child.close()
436
437
326 @skip_win32
438 @skip_win32
327 def test_where_erase_value():
439 def test_where_erase_value():
328 """Test that `where` does not access f_locals and erase values."""
440 """Test that `where` does not access f_locals and erase values."""
329 import pexpect
441 import pexpect
330
442
331 env = os.environ.copy()
443 env = os.environ.copy()
332 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
444 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
333
445
334 child = pexpect.spawn(
446 child = pexpect.spawn(
335 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
447 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
336 )
448 )
337 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
449 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
338
450
339 child.expect("IPython")
451 child.expect("IPython")
340 child.expect("\n")
452 child.expect("\n")
341 child.expect_exact("In [1]")
453 child.expect_exact("In [1]")
342
454
343 block = dedent(
455 block = dedent(
344 """
456 """
345 def simple_f():
457 def simple_f():
346 myvar = 1
458 myvar = 1
347 print(myvar)
459 print(myvar)
348 1/0
460 1/0
349 print(myvar)
461 print(myvar)
350 simple_f() """
462 simple_f() """
351 )
463 )
352
464
353 for line in block.splitlines():
465 for line in block.splitlines():
354 child.sendline(line)
466 child.sendline(line)
355 child.expect_exact(line)
467 child.expect_exact(line)
356 child.expect_exact("ZeroDivisionError")
468 child.expect_exact("ZeroDivisionError")
357 child.expect_exact("In [2]:")
469 child.expect_exact("In [2]:")
358
470
359 child.sendline("%debug")
471 child.sendline("%debug")
360
472
361 ##
473 ##
362 child.expect("ipdb>")
474 child.expect("ipdb>")
363
475
364 child.sendline("myvar")
476 child.sendline("myvar")
365 child.expect("1")
477 child.expect("1")
366
478
367 ##
479 ##
368 child.expect("ipdb>")
480 child.expect("ipdb>")
369
481
370 child.sendline("myvar = 2")
482 child.sendline("myvar = 2")
371
483
372 ##
484 ##
373 child.expect_exact("ipdb>")
485 child.expect_exact("ipdb>")
374
486
375 child.sendline("myvar")
487 child.sendline("myvar")
376
488
377 child.expect_exact("2")
489 child.expect_exact("2")
378
490
379 ##
491 ##
380 child.expect("ipdb>")
492 child.expect("ipdb>")
381 child.sendline("where")
493 child.sendline("where")
382
494
383 ##
495 ##
384 child.expect("ipdb>")
496 child.expect("ipdb>")
385 child.sendline("myvar")
497 child.sendline("myvar")
386
498
387 child.expect_exact("2")
499 child.expect_exact("2")
388 child.expect("ipdb>")
500 child.expect("ipdb>")
389
501
390 child.close()
502 child.close()
@@ -1,166 +1,164 b''
1 import asyncio
1 import asyncio
2 import sys
2 import sys
3 import threading
3 import threading
4
4
5 from IPython.core.debugger import Pdb
5 from IPython.core.debugger import Pdb
6
6
7 from IPython.core.completer import IPCompleter
7 from IPython.core.completer import IPCompleter
8 from .ptutils import IPythonPTCompleter
8 from .ptutils import IPythonPTCompleter
9 from .shortcuts import create_ipython_shortcuts
9 from .shortcuts import create_ipython_shortcuts
10 from . import embed
10 from . import embed
11
11
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
16
17 from prompt_toolkit import __version__ as ptk_version
17 from prompt_toolkit import __version__ as ptk_version
18 PTK3 = ptk_version.startswith('3.')
18 PTK3 = ptk_version.startswith('3.')
19
19
20
20
21 class TerminalPdb(Pdb):
21 class TerminalPdb(Pdb):
22 """Standalone IPython debugger."""
22 """Standalone IPython debugger."""
23
23
24 def __init__(self, *args, pt_session_options=None, **kwargs):
24 def __init__(self, *args, pt_session_options=None, **kwargs):
25 Pdb.__init__(self, *args, **kwargs)
25 Pdb.__init__(self, *args, **kwargs)
26 self._ptcomp = None
26 self._ptcomp = None
27 self.pt_init(pt_session_options)
27 self.pt_init(pt_session_options)
28
28
29 def pt_init(self, pt_session_options=None):
29 def pt_init(self, pt_session_options=None):
30 """Initialize the prompt session and the prompt loop
30 """Initialize the prompt session and the prompt loop
31 and store them in self.pt_app and self.pt_loop.
31 and store them in self.pt_app and self.pt_loop.
32
32
33 Additional keyword arguments for the PromptSession class
33 Additional keyword arguments for the PromptSession class
34 can be specified in pt_session_options.
34 can be specified in pt_session_options.
35 """
35 """
36 if pt_session_options is None:
36 if pt_session_options is None:
37 pt_session_options = {}
37 pt_session_options = {}
38
38
39 def get_prompt_tokens():
39 def get_prompt_tokens():
40 return [(Token.Prompt, self.prompt)]
40 return [(Token.Prompt, self.prompt)]
41
41
42 if self._ptcomp is None:
42 if self._ptcomp is None:
43 compl = IPCompleter(
43 compl = IPCompleter(
44 shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
44 shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
45 )
45 )
46 # add a completer for all the do_ methods
46 # add a completer for all the do_ methods
47 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
47 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
48
48
49 def gen_comp(self, text):
49 def gen_comp(self, text):
50 return [m for m in methods_names if m.startswith(text)]
50 return [m for m in methods_names if m.startswith(text)]
51 import types
51 import types
52 newcomp = types.MethodType(gen_comp, compl)
52 newcomp = types.MethodType(gen_comp, compl)
53 compl.custom_matchers.insert(0, newcomp)
53 compl.custom_matchers.insert(0, newcomp)
54 # end add completer.
54 # end add completer.
55
55
56 self._ptcomp = IPythonPTCompleter(compl)
56 self._ptcomp = IPythonPTCompleter(compl)
57
57
58 options = dict(
58 options = dict(
59 message=(lambda: PygmentsTokens(get_prompt_tokens())),
59 message=(lambda: PygmentsTokens(get_prompt_tokens())),
60 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
60 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
61 key_bindings=create_ipython_shortcuts(self.shell),
61 key_bindings=create_ipython_shortcuts(self.shell),
62 history=self.shell.debugger_history,
62 history=self.shell.debugger_history,
63 completer=self._ptcomp,
63 completer=self._ptcomp,
64 enable_history_search=True,
64 enable_history_search=True,
65 mouse_support=self.shell.mouse_support,
65 mouse_support=self.shell.mouse_support,
66 complete_style=self.shell.pt_complete_style,
66 complete_style=self.shell.pt_complete_style,
67 style=self.shell.style,
67 style=getattr(self.shell, "style", None),
68 color_depth=self.shell.color_depth,
68 color_depth=self.shell.color_depth,
69 )
69 )
70
70
71 if not PTK3:
71 if not PTK3:
72 options['inputhook'] = self.shell.inputhook
72 options['inputhook'] = self.shell.inputhook
73 options.update(pt_session_options)
73 options.update(pt_session_options)
74 self.pt_loop = asyncio.new_event_loop()
74 self.pt_loop = asyncio.new_event_loop()
75 self.pt_app = PromptSession(**options)
75 self.pt_app = PromptSession(**options)
76
76
77 def cmdloop(self, intro=None):
77 def cmdloop(self, intro=None):
78 """Repeatedly issue a prompt, accept input, parse an initial prefix
78 """Repeatedly issue a prompt, accept input, parse an initial prefix
79 off the received input, and dispatch to action methods, passing them
79 off the received input, and dispatch to action methods, passing them
80 the remainder of the line as argument.
80 the remainder of the line as argument.
81
81
82 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
82 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
83 """
83 """
84 if not self.use_rawinput:
84 if not self.use_rawinput:
85 raise ValueError('Sorry ipdb does not support use_rawinput=False')
85 raise ValueError('Sorry ipdb does not support use_rawinput=False')
86
86
87 # In order to make sure that prompt, which uses asyncio doesn't
87 # In order to make sure that prompt, which uses asyncio doesn't
88 # interfere with applications in which it's used, we always run the
88 # interfere with applications in which it's used, we always run the
89 # prompt itself in a different thread (we can't start an event loop
89 # prompt itself in a different thread (we can't start an event loop
90 # within an event loop). This new thread won't have any event loop
90 # within an event loop). This new thread won't have any event loop
91 # running, and here we run our prompt-loop.
91 # running, and here we run our prompt-loop.
92
93 self.preloop()
92 self.preloop()
94
93
95 try:
94 try:
96 if intro is not None:
95 if intro is not None:
97 self.intro = intro
96 self.intro = intro
98 if self.intro:
97 if self.intro:
99 self.stdout.write(str(self.intro)+"\n")
98 self.stdout.write(str(self.intro)+"\n")
100 stop = None
99 stop = None
101 while not stop:
100 while not stop:
102 if self.cmdqueue:
101 if self.cmdqueue:
103 line = self.cmdqueue.pop(0)
102 line = self.cmdqueue.pop(0)
104 else:
103 else:
105 self._ptcomp.ipy_completer.namespace = self.curframe_locals
104 self._ptcomp.ipy_completer.namespace = self.curframe_locals
106 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
105 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
107
106
108 # Run the prompt in a different thread.
107 # Run the prompt in a different thread.
109 line = ''
108 line = ''
110 keyboard_interrupt = False
109 keyboard_interrupt = False
111
110
112 def in_thread():
111 def in_thread():
113 nonlocal line, keyboard_interrupt
112 nonlocal line, keyboard_interrupt
114 try:
113 try:
115 line = self.pt_app.prompt()
114 line = self.pt_app.prompt()
116 except EOFError:
115 except EOFError:
117 line = 'EOF'
116 line = 'EOF'
118 except KeyboardInterrupt:
117 except KeyboardInterrupt:
119 keyboard_interrupt = True
118 keyboard_interrupt = True
120
119
121 th = threading.Thread(target=in_thread)
120 th = threading.Thread(target=in_thread)
122 th.start()
121 th.start()
123 th.join()
122 th.join()
124
123
125 if keyboard_interrupt:
124 if keyboard_interrupt:
126 raise KeyboardInterrupt
125 raise KeyboardInterrupt
127
128 line = self.precmd(line)
126 line = self.precmd(line)
129 stop = self.onecmd(line)
127 stop = self.onecmd(line)
130 stop = self.postcmd(stop, line)
128 stop = self.postcmd(stop, line)
131 self.postloop()
129 self.postloop()
132 except Exception:
130 except Exception:
133 raise
131 raise
134
132
135 def do_interact(self, arg):
133 def do_interact(self, arg):
136 ipshell = embed.InteractiveShellEmbed(
134 ipshell = embed.InteractiveShellEmbed(
137 config=self.shell.config,
135 config=self.shell.config,
138 banner1="*interactive*",
136 banner1="*interactive*",
139 exit_msg="*exiting interactive console...*",
137 exit_msg="*exiting interactive console...*",
140 )
138 )
141 global_ns = self.curframe.f_globals
139 global_ns = self.curframe.f_globals
142 ipshell(
140 ipshell(
143 module=sys.modules.get(global_ns["__name__"], None),
141 module=sys.modules.get(global_ns["__name__"], None),
144 local_ns=self.curframe_locals,
142 local_ns=self.curframe_locals,
145 )
143 )
146
144
147
145
148 def set_trace(frame=None):
146 def set_trace(frame=None):
149 """
147 """
150 Start debugging from `frame`.
148 Start debugging from `frame`.
151
149
152 If frame is not specified, debugging starts from caller's frame.
150 If frame is not specified, debugging starts from caller's frame.
153 """
151 """
154 TerminalPdb().set_trace(frame or sys._getframe().f_back)
152 TerminalPdb().set_trace(frame or sys._getframe().f_back)
155
153
156
154
157 if __name__ == '__main__':
155 if __name__ == '__main__':
158 import pdb
156 import pdb
159 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
157 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
160 # bdb.BdbQuit. When started through __main__ and an exception
158 # bdb.BdbQuit. When started through __main__ and an exception
161 # happened after hitting "c", this is needed in order to
159 # happened after hitting "c", this is needed in order to
162 # be able to quit the debugging session (see #9950).
160 # be able to quit the debugging session (see #9950).
163 old_trace_dispatch = pdb.Pdb.trace_dispatch
161 old_trace_dispatch = pdb.Pdb.trace_dispatch
164 pdb.Pdb = TerminalPdb # type: ignore
162 pdb.Pdb = TerminalPdb # type: ignore
165 pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
163 pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
166 pdb.main()
164 pdb.main()
@@ -1,1563 +1,1564 b''
1 ============
1 ============
2 7.x Series
2 7.x Series
3 ============
3 ============
4
4
5
5 .. _version 7.28:
6 .. _version 7.28:
6
7
7 IPython 7.28
8 IPython 7.28
8 ============
9 ============
9
10
10
11
11 IPython 7.28 is again a minor release that mostly bring bugfixes, and couple of
12 IPython 7.28 is again a minor release that mostly bring bugfixes, and couple of
12 improvement. Many thanks to MrMino, who again did all the work this month, and
13 improvement. Many thanks to MrMino, who again did all the work this month, and
13 made a number of documentation improvements.
14 made a number of documentation improvements.
14
15
15 Here is a non-exhaustive list of changes,
16 Here is a non-exhaustive list of changes,
16
17
17 Fixes:
18 Fixes:
18
19
19 - async with doesn't allow newlines :ghpull:`13090`
20 - async with doesn't allow newlines :ghpull:`13090`
20 - Dynamically changing to vi mode via %config magic) :ghpull:`13091`
21 - Dynamically changing to vi mode via %config magic) :ghpull:`13091`
21
22
22 Virtualenv handling fixes:
23 Virtualenv handling fixes:
23
24
24 - init_virtualenv now uses Pathlib :ghpull:`12548`
25 - init_virtualenv now uses Pathlib :ghpull:`12548`
25 - Fix Improper path comparison of virtualenv directories :ghpull:`13140`
26 - Fix Improper path comparison of virtualenv directories :ghpull:`13140`
26 - Fix virtual environment user warning for lower case pathes :ghpull:`13094`
27 - Fix virtual environment user warning for lower case pathes :ghpull:`13094`
27 - Adapt to all sorts of drive names for cygwin :ghpull:`13153`
28 - Adapt to all sorts of drive names for cygwin :ghpull:`13153`
28
29
29 New Features:
30 New Features:
30
31
31 - enable autoplay in embed YouTube player :ghpull:`13133`
32 - enable autoplay in embed YouTube player :ghpull:`13133`
32
33
33 Documentation:
34 Documentation:
34
35
35 - Fix formatting for the core.interactiveshell documentation :ghpull:`13118`
36 - Fix formatting for the core.interactiveshell documentation :ghpull:`13118`
36 - Fix broken ipyparallel's refs :ghpull:`13138`
37 - Fix broken ipyparallel's refs :ghpull:`13138`
37 - Improve formatting of %time documentation :ghpull:`13125`
38 - Improve formatting of %time documentation :ghpull:`13125`
38 - Reword the YouTubeVideo autoplay WN :ghpull:`13147`
39 - Reword the YouTubeVideo autoplay WN :ghpull:`13147`
39
40
40
41
41 Thanks
42 Thanks
42 ------
43 ------
43
44
44 Many thanks to all the contributors to this release. You can find all individual
45 Many thanks to all the contributors to this release. You can find all individual
45 contributions to this milestone `on github
46 contributions to this milestone `on github
46 <https://github.com/ipython/ipython/milestone/92>`__.
47 <https://github.com/ipython/ipython/milestone/92>`__.
47
48
48 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
49 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
49 work on IPython and related libraries.
50 work on IPython and related libraries.
50
51
51
52
52 .. _version 7.27:
53 .. _version 7.27:
53
54
54 IPython 7.27
55 IPython 7.27
55 ============
56 ============
56
57
57 IPython 7.27 is a minor release that fixes a couple of issues and compatibility.
58 IPython 7.27 is a minor release that fixes a couple of issues and compatibility.
58
59
59 - Add support for GTK4 :ghpull:`131011`
60 - Add support for GTK4 :ghpull:`131011`
60 - Add support for Qt6 :ghpull:`13085`
61 - Add support for Qt6 :ghpull:`13085`
61 - Fix an issue with pip magic on windows :ghpull:`13093`
62 - Fix an issue with pip magic on windows :ghpull:`13093`
62
63
63 Thanks
64 Thanks
64 ------
65 ------
65
66
66 Many thanks to all the contributors to this release. You can find all individual
67 Many thanks to all the contributors to this release. You can find all individual
67 contributions to this milestone `on github
68 contributions to this milestone `on github
68 <https://github.com/ipython/ipython/milestone/91>`__.
69 <https://github.com/ipython/ipython/milestone/91>`__.
69
70
70 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
71 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
71 work on IPython and related libraries.
72 work on IPython and related libraries.
72
73
73 .. _version 7.26:
74 .. _version 7.26:
74
75
75 IPython 7.26
76 IPython 7.26
76 ============
77 ============
77
78
78 IPython 7.26 is a minor release that fixes a couple of issues, updates in API
79 IPython 7.26 is a minor release that fixes a couple of issues, updates in API
79 and Copyright/Licenses issues around various part of the codebase.
80 and Copyright/Licenses issues around various part of the codebase.
80
81
81 We'll highlight `this issue <https://github.com/ipython/ipython/issues/13039>`
82 We'll highlight `this issue <https://github.com/ipython/ipython/issues/13039>`
82 pointing out we were including and refereeing to code from Stack Overflow which
83 pointing out we were including and refereeing to code from Stack Overflow which
83 was CC-BY-SA, hence incompatible with the BSD license of IPython. This lead us
84 was CC-BY-SA, hence incompatible with the BSD license of IPython. This lead us
84 to a rewriting of the corresponding logic which in our case was done in a more
85 to a rewriting of the corresponding logic which in our case was done in a more
85 efficient way (in our case we were searching string prefixes instead of full
86 efficient way (in our case we were searching string prefixes instead of full
86 strings).
87 strings).
87
88
88 You will notice also a number of documentation improvements and cleanup.
89 You will notice also a number of documentation improvements and cleanup.
89
90
90 Of particular interest are the following Pull-requests:
91 Of particular interest are the following Pull-requests:
91
92
92
93
93 - The IPython directive now uses Sphinx logging for warnings. :ghpull:`13030`.
94 - The IPython directive now uses Sphinx logging for warnings. :ghpull:`13030`.
94 - Add expiry days option to pastebin magic and change http protocol to https.
95 - Add expiry days option to pastebin magic and change http protocol to https.
95 :ghpull:`13056`
96 :ghpull:`13056`
96 - Make Ipython.utils.timing work with jupyterlite :ghpull:`13050`.
97 - Make Ipython.utils.timing work with jupyterlite :ghpull:`13050`.
97
98
98
99
99
100
100 Thanks
101 Thanks
101 ------
102 ------
102
103
103 Many thanks to all the contributors to this release and in particular MrMino who
104 Many thanks to all the contributors to this release and in particular MrMino who
104 is doing most of the work those days. You can find all individual contributions
105 is doing most of the work those days. You can find all individual contributions
105 to this milestone `on github <https://github.com/ipython/ipython/milestone/90>`__.
106 to this milestone `on github <https://github.com/ipython/ipython/milestone/90>`__.
106
107
107 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
108 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
108 work on IPython and related libraries.
109 work on IPython and related libraries.
109
110
110
111
111 .. _version 7.25:
112 .. _version 7.25:
112
113
113 IPython 7.25
114 IPython 7.25
114 ============
115 ============
115
116
116 IPython 7.25 is a minor release that contains a single bugfix, which is highly
117 IPython 7.25 is a minor release that contains a single bugfix, which is highly
117 recommended for all users of ipdb, ipython debugger %debug magic and similar.
118 recommended for all users of ipdb, ipython debugger %debug magic and similar.
118
119
119 Issuing commands like ``where`` from within the debugger would reset the
120 Issuing commands like ``where`` from within the debugger would reset the
120 local variables changes made by the user. It is interesting to look at the root
121 local variables changes made by the user. It is interesting to look at the root
121 cause of the issue as accessing an attribute (``frame.f_locals``) would trigger
122 cause of the issue as accessing an attribute (``frame.f_locals``) would trigger
122 this side effects.
123 this side effects.
123
124
124 Thanks in particular to the patience from the reporters at D.E. Shaw for their
125 Thanks in particular to the patience from the reporters at D.E. Shaw for their
125 initial bug report that was due to a similar coding oversight in an extension,
126 initial bug report that was due to a similar coding oversight in an extension,
126 and who took time to debug and narrow down the problem.
127 and who took time to debug and narrow down the problem.
127
128
128 Thanks
129 Thanks
129 ------
130 ------
130
131
131 Many thanks to all the contributors to this release you can find all individual
132 Many thanks to all the contributors to this release you can find all individual
132 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/89>`__.
133 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/89>`__.
133
134
134 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
135 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
135 work on IPython and related libraries.
136 work on IPython and related libraries.
136
137
137
138
138 .. _version 7.24:
139 .. _version 7.24:
139
140
140 IPython 7.24
141 IPython 7.24
141 ============
142 ============
142
143
143 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
144 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
144 typical updates:
145 typical updates:
145
146
146 Misc
147 Misc
147 ----
148 ----
148
149
149
150
150 - Fix an issue where ``%recall`` would both succeeded and print an error message
151 - Fix an issue where ``%recall`` would both succeeded and print an error message
151 it failed. :ghpull:`12952`
152 it failed. :ghpull:`12952`
152 - Drop support for NumPy 1.16 – practically has no effect beyond indicating in
153 - Drop support for NumPy 1.16 – practically has no effect beyond indicating in
153 package metadata that we do not support it. :ghpull:`12937`
154 package metadata that we do not support it. :ghpull:`12937`
154
155
155 Debugger improvements
156 Debugger improvements
156 ---------------------
157 ---------------------
157
158
158 The debugger (and ``%debug`` magic) have been improved and can skip or hide frames
159 The debugger (and ``%debug`` magic) have been improved and can skip or hide frames
159 originating from files that are not writable to the user, as these are less
160 originating from files that are not writable to the user, as these are less
160 likely to be the source of errors, or be part of system files this can be a useful
161 likely to be the source of errors, or be part of system files this can be a useful
161 addition when debugging long errors.
162 addition when debugging long errors.
162
163
163 In addition to the global ``skip_hidden True|False`` command, the debugger has
164 In addition to the global ``skip_hidden True|False`` command, the debugger has
164 gained finer grained control of predicates as to whether to a frame should be
165 gained finer grained control of predicates as to whether to a frame should be
165 considered hidden. So far 3 predicates are available :
166 considered hidden. So far 3 predicates are available :
166
167
167 - ``tbhide``: frames containing the local variable ``__tracebackhide__`` set to
168 - ``tbhide``: frames containing the local variable ``__tracebackhide__`` set to
168 True.
169 True.
169 - ``readonly``: frames originating from readonly files, set to False.
170 - ``readonly``: frames originating from readonly files, set to False.
170 - ``ipython_internal``: frames that are likely to be from IPython internal
171 - ``ipython_internal``: frames that are likely to be from IPython internal
171 code, set to True.
172 code, set to True.
172
173
173 You can toggle individual predicates during a session with
174 You can toggle individual predicates during a session with
174
175
175 .. code-block::
176 .. code-block::
176
177
177 ipdb> skip_predicates readonly True
178 ipdb> skip_predicates readonly True
178
179
179 Read-only files will now be considered hidden frames.
180 Read-only files will now be considered hidden frames.
180
181
181
182
182 You can call ``skip_predicates`` without arguments to see the states of current
183 You can call ``skip_predicates`` without arguments to see the states of current
183 predicates:
184 predicates:
184
185
185 .. code-block::
186 .. code-block::
186
187
187 ipdb> skip_predicates
188 ipdb> skip_predicates
188 current predicates:
189 current predicates:
189 tbhide : True
190 tbhide : True
190 readonly : False
191 readonly : False
191 ipython_internal : True
192 ipython_internal : True
192
193
193 If all predicates are set to ``False``, ``skip_hidden`` will practically have
194 If all predicates are set to ``False``, ``skip_hidden`` will practically have
194 no effect. We attempt to warn you when all predicates are False.
195 no effect. We attempt to warn you when all predicates are False.
195
196
196 Note that the ``readonly`` predicate may increase disk access as we check for
197 Note that the ``readonly`` predicate may increase disk access as we check for
197 file access permission for all frames on many command invocation, but is usually
198 file access permission for all frames on many command invocation, but is usually
198 cached by operating systems. Let us know if you encounter any issues.
199 cached by operating systems. Let us know if you encounter any issues.
199
200
200 As the IPython debugger does not use the traitlets infrastructure for
201 As the IPython debugger does not use the traitlets infrastructure for
201 configuration, by editing your ``.pdbrc`` files and appending commands you would
202 configuration, by editing your ``.pdbrc`` files and appending commands you would
202 like to be executed just before entering the interactive prompt. For example:
203 like to be executed just before entering the interactive prompt. For example:
203
204
204
205
205 .. code::
206 .. code::
206
207
207 # file : ~/.pdbrc
208 # file : ~/.pdbrc
208 skip_predicates readonly True
209 skip_predicates readonly True
209 skip_predicates tbhide False
210 skip_predicates tbhide False
210
211
211 Will hide read only frames by default and show frames marked with
212 Will hide read only frames by default and show frames marked with
212 ``__tracebackhide__``.
213 ``__tracebackhide__``.
213
214
214
215
215
216
216
217
217 Thanks
218 Thanks
218 ------
219 ------
219
220
220 Many thanks to all the contributors to this release you can find all individual
221 Many thanks to all the contributors to this release you can find all individual
221 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/87>`__.
222 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/87>`__.
222
223
223 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
224 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
224 work on IPython and related libraries, in particular above mentioned
225 work on IPython and related libraries, in particular above mentioned
225 improvements to the debugger.
226 improvements to the debugger.
226
227
227
228
228
229
229
230
230 .. _version 7.23:
231 .. _version 7.23:
231
232
232 IPython 7.23 and 7.23.1
233 IPython 7.23 and 7.23.1
233 =======================
234 =======================
234
235
235
236
236 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
237 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
237 typical updates:
238 typical updates:
238
239
239 - We moved to GitHub actions away from Travis-CI, the transition may not be
240 - We moved to GitHub actions away from Travis-CI, the transition may not be
240 100% complete (not testing on nightly anymore), but as we ran out of
241 100% complete (not testing on nightly anymore), but as we ran out of
241 Travis-Ci hours on the IPython organisation that was a necessary step.
242 Travis-Ci hours on the IPython organisation that was a necessary step.
242 :ghpull:`12900`.
243 :ghpull:`12900`.
243
244
244 - We have a new dependency: ``matplotlib-inline``, which try to extract
245 - We have a new dependency: ``matplotlib-inline``, which try to extract
245 matplotlib inline backend specific behavior. It is available on PyPI and
246 matplotlib inline backend specific behavior. It is available on PyPI and
246 conda-forge thus should not be a problem to upgrade to this version. If you
247 conda-forge thus should not be a problem to upgrade to this version. If you
247 are a package maintainer that might be an extra dependency to package first.
248 are a package maintainer that might be an extra dependency to package first.
248 :ghpull:`12817` (IPython 7.23.1 fix a typo that made this change fail)
249 :ghpull:`12817` (IPython 7.23.1 fix a typo that made this change fail)
249
250
250 In the addition/new feature category, ``display()`` now have a ``clear=True``
251 In the addition/new feature category, ``display()`` now have a ``clear=True``
251 option to clear the display if any further outputs arrives, allowing users to
252 option to clear the display if any further outputs arrives, allowing users to
252 avoid having to use ``clear_output()`` directly. :ghpull:`12823`.
253 avoid having to use ``clear_output()`` directly. :ghpull:`12823`.
253
254
254 In bug fixes category, this release fix an issue when printing tracebacks
255 In bug fixes category, this release fix an issue when printing tracebacks
255 containing Unicode characters :ghpull:`12758`.
256 containing Unicode characters :ghpull:`12758`.
256
257
257 In code cleanup category :ghpull:`12932` remove usage of some deprecated
258 In code cleanup category :ghpull:`12932` remove usage of some deprecated
258 functionality for compatibility with Python 3.10.
259 functionality for compatibility with Python 3.10.
259
260
260
261
261
262
262 Thanks
263 Thanks
263 ------
264 ------
264
265
265 Many thanks to all the contributors to this release you can find all individual
266 Many thanks to all the contributors to this release you can find all individual
266 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/86>`__.
267 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/86>`__.
267 In particular MrMino for responding to almost all new issues, and triaging many
268 In particular MrMino for responding to almost all new issues, and triaging many
268 of the old ones, as well as takluyver, minrk, willingc for reacting quikly when
269 of the old ones, as well as takluyver, minrk, willingc for reacting quikly when
269 we ran out of CI Hours.
270 we ran out of CI Hours.
270
271
271 Thanks as well to organisations, QuantStack (martinRenou and SylvainCorlay) for
272 Thanks as well to organisations, QuantStack (martinRenou and SylvainCorlay) for
272 extracting matplotlib inline backend into its own package, and the `D. E. Shaw group
273 extracting matplotlib inline backend into its own package, and the `D. E. Shaw group
273 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
274 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
274
275
275
276
276 .. _version 7.22:
277 .. _version 7.22:
277
278
278 IPython 7.22
279 IPython 7.22
279 ============
280 ============
280
281
281 Second release of IPython for 2021, mostly containing bug fixes. Here is a quick
282 Second release of IPython for 2021, mostly containing bug fixes. Here is a quick
282 rundown of the few changes.
283 rundown of the few changes.
283
284
284 - Fix some ``sys.excepthook`` shenanigan when embedding with qt, recommended if
285 - Fix some ``sys.excepthook`` shenanigan when embedding with qt, recommended if
285 you – for example – use `napari <https://napari.org>`__. :ghpull:`12842`.
286 you – for example – use `napari <https://napari.org>`__. :ghpull:`12842`.
286 - Fix bug when using the new ipdb ``%context`` magic :ghpull:`12844`
287 - Fix bug when using the new ipdb ``%context`` magic :ghpull:`12844`
287 - Couples of deprecation cleanup :ghpull:`12868`
288 - Couples of deprecation cleanup :ghpull:`12868`
288 - Update for new dpast.com api if you use the ``%pastbin`` magic. :ghpull:`12712`
289 - Update for new dpast.com api if you use the ``%pastbin`` magic. :ghpull:`12712`
289 - Remove support for numpy before 1.16. :ghpull:`12836`
290 - Remove support for numpy before 1.16. :ghpull:`12836`
290
291
291
292
292 Thanks
293 Thanks
293 ------
294 ------
294
295
295 We have a new team member that you should see more often on the IPython
296 We have a new team member that you should see more often on the IPython
296 repository, BΕ‚aΕΌej Michalik (@MrMino) have been doing regular contributions to
297 repository, BΕ‚aΕΌej Michalik (@MrMino) have been doing regular contributions to
297 IPython, and spent time replying to many issues and guiding new users to the
298 IPython, and spent time replying to many issues and guiding new users to the
298 codebase; they now have triage permissions to the IPython repository and we'll
299 codebase; they now have triage permissions to the IPython repository and we'll
299 work toward giving them more permission in the future.
300 work toward giving them more permission in the future.
300
301
301 Many thanks to all the contributors to this release you can find all individual
302 Many thanks to all the contributors to this release you can find all individual
302 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/84>`__.
303 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/84>`__.
303
304
304 Thanks as well to organisations, QuantStack for working on debugger
305 Thanks as well to organisations, QuantStack for working on debugger
305 compatibility for Xeus_python, and the `D. E. Shaw group
306 compatibility for Xeus_python, and the `D. E. Shaw group
306 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
307 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
307
308
308 .. _version 721:
309 .. _version 721:
309
310
310 IPython 7.21
311 IPython 7.21
311 ============
312 ============
312
313
313 IPython 7.21 is the first release we have back on schedule of one release every
314 IPython 7.21 is the first release we have back on schedule of one release every
314 month; it contains a number of minor fixes and improvements, notably, the new
315 month; it contains a number of minor fixes and improvements, notably, the new
315 context command for ipdb
316 context command for ipdb
316
317
317
318
318 New "context" command in ipdb
319 New "context" command in ipdb
319 -----------------------------
320 -----------------------------
320
321
321 It is now possible to change the number of lines shown in the backtrace
322 It is now possible to change the number of lines shown in the backtrace
322 information in ipdb using "context" command. :ghpull:`12826`
323 information in ipdb using "context" command. :ghpull:`12826`
323
324
324 (thanks @MrMino, there are other improvement from them on master).
325 (thanks @MrMino, there are other improvement from them on master).
325
326
326 Other notable changes in IPython 7.21
327 Other notable changes in IPython 7.21
327 -------------------------------------
328 -------------------------------------
328
329
329 - Fix some issues on new osx-arm64 :ghpull:`12804`, :ghpull:`12807`.
330 - Fix some issues on new osx-arm64 :ghpull:`12804`, :ghpull:`12807`.
330 - Compatibility with Xeus-Python for debugger protocol, :ghpull:`12809`
331 - Compatibility with Xeus-Python for debugger protocol, :ghpull:`12809`
331 - Misc docs fixes for compatibility and uniformity with Numpydoc.
332 - Misc docs fixes for compatibility and uniformity with Numpydoc.
332 :ghpull:`12824`
333 :ghpull:`12824`
333
334
334
335
335 Thanks
336 Thanks
336 ------
337 ------
337
338
338 Many thanks to all the contributors to this release you can find all individual
339 Many thanks to all the contributors to this release you can find all individual
339 contribution to this milestone `on github <https://github.com/ipython/ipython/milestone/83>`__.
340 contribution to this milestone `on github <https://github.com/ipython/ipython/milestone/83>`__.
340
341
341
342
342 .. _version 720:
343 .. _version 720:
343
344
344 IPython 7.20
345 IPython 7.20
345 ============
346 ============
346
347
347 IPython 7.20 is the accumulation of 3 month of work on IPython, spacing between
348 IPython 7.20 is the accumulation of 3 month of work on IPython, spacing between
348 IPython release have been increased from the usual once a month for various
349 IPython release have been increased from the usual once a month for various
349 reason.
350 reason.
350
351
351 - Mainly as I'm too busy and the effectively sole maintainer, and
352 - Mainly as I'm too busy and the effectively sole maintainer, and
352 - Second because not much changes happened before mid December.
353 - Second because not much changes happened before mid December.
353
354
354 The main driver for this release was the new version of Jedi 0.18 breaking API;
355 The main driver for this release was the new version of Jedi 0.18 breaking API;
355 which was taken care of in the master branch early in 2020 but not in 7.x as I
356 which was taken care of in the master branch early in 2020 but not in 7.x as I
356 though that by now 8.0 would be out.
357 though that by now 8.0 would be out.
357
358
358 The inclusion of a resolver in pip did not help and actually made things worse.
359 The inclusion of a resolver in pip did not help and actually made things worse.
359 If usually I would have simply pinned Jedi to ``<0.18``; this is not a solution
360 If usually I would have simply pinned Jedi to ``<0.18``; this is not a solution
360 anymore as now pip is free to install Jedi 0.18, and downgrade IPython.
361 anymore as now pip is free to install Jedi 0.18, and downgrade IPython.
361
362
362 I'll do my best to keep the regular release, but as the 8.0-dev branch and 7.x
363 I'll do my best to keep the regular release, but as the 8.0-dev branch and 7.x
363 are starting to diverge this is becoming difficult in particular with my limited
364 are starting to diverge this is becoming difficult in particular with my limited
364 time, so if you have any cycles to spare I'll appreciate your help to respond to
365 time, so if you have any cycles to spare I'll appreciate your help to respond to
365 issues and pushing 8.0 forward.
366 issues and pushing 8.0 forward.
366
367
367 Here are thus some of the changes for IPython 7.20.
368 Here are thus some of the changes for IPython 7.20.
368
369
369 - Support for PyQt5 >= 5.11 :ghpull:`12715`
370 - Support for PyQt5 >= 5.11 :ghpull:`12715`
370 - ``%reset`` remove imports more agressively :ghpull:`12718`
371 - ``%reset`` remove imports more agressively :ghpull:`12718`
371 - fix the ``%conda`` magic :ghpull:`12739`
372 - fix the ``%conda`` magic :ghpull:`12739`
372 - compatibility with Jedi 0.18, and bump minimum Jedi version. :ghpull:`12793`
373 - compatibility with Jedi 0.18, and bump minimum Jedi version. :ghpull:`12793`
373
374
374
375
375 .. _version 719:
376 .. _version 719:
376
377
377 IPython 7.19
378 IPython 7.19
378 ============
379 ============
379
380
380 IPython 7.19 accumulative two month of works, bug fixes and improvements, there
381 IPython 7.19 accumulative two month of works, bug fixes and improvements, there
381 was exceptionally no release last month.
382 was exceptionally no release last month.
382
383
383 - Fix to restore the ability to specify more than one extension using command
384 - Fix to restore the ability to specify more than one extension using command
384 line flags when using traitlets 5.0 :ghpull:`12543`
385 line flags when using traitlets 5.0 :ghpull:`12543`
385 - Docs docs formatting that make the install commands work on zsh
386 - Docs docs formatting that make the install commands work on zsh
386 :ghpull:`12587`
387 :ghpull:`12587`
387 - Always display the last frame in tracebacks even if hidden with
388 - Always display the last frame in tracebacks even if hidden with
388 ``__tracebackhide__`` :ghpull:`12601`
389 ``__tracebackhide__`` :ghpull:`12601`
389 - Avoid an issue where a callback can be registered multiple times.
390 - Avoid an issue where a callback can be registered multiple times.
390 :ghpull:`12625`
391 :ghpull:`12625`
391 - Avoid an issue in debugger mode where frames changes could be lost.
392 - Avoid an issue in debugger mode where frames changes could be lost.
392 :ghpull:`12627`
393 :ghpull:`12627`
393
394
394 - Never hide the frames that invoke a debugger, even if marked as hidden by
395 - Never hide the frames that invoke a debugger, even if marked as hidden by
395 ``__tracebackhide__`` :ghpull:`12631`
396 ``__tracebackhide__`` :ghpull:`12631`
396 - Fix calling the debugger in a recursive manner :ghpull:`12659`
397 - Fix calling the debugger in a recursive manner :ghpull:`12659`
397
398
398
399
399 A number of code changes have landed on master and we are getting close to
400 A number of code changes have landed on master and we are getting close to
400 enough new features and codebase improvement that a 8.0 start to make sens.
401 enough new features and codebase improvement that a 8.0 start to make sens.
401 For downstream packages, please start working on migrating downstream testing
402 For downstream packages, please start working on migrating downstream testing
402 away from iptest and using pytest, as nose will not work on Python 3.10 and we
403 away from iptest and using pytest, as nose will not work on Python 3.10 and we
403 will likely start removing it as a dependency for testing.
404 will likely start removing it as a dependency for testing.
404
405
405 .. _version 718:
406 .. _version 718:
406
407
407 IPython 7.18
408 IPython 7.18
408 ============
409 ============
409
410
410 IPython 7.18 is a minor release that mostly contains bugfixes.
411 IPython 7.18 is a minor release that mostly contains bugfixes.
411
412
412 - ``CRLF`` is now handled by magics my default; solving some issues due to copy
413 - ``CRLF`` is now handled by magics my default; solving some issues due to copy
413 pasting on windows. :ghpull:`12475`
414 pasting on windows. :ghpull:`12475`
414
415
415 - Requiring pexpect ``>=4.3`` as we are Python 3.7+ only and earlier version of
416 - Requiring pexpect ``>=4.3`` as we are Python 3.7+ only and earlier version of
416 pexpect will be incompatible. :ghpull:`12510`
417 pexpect will be incompatible. :ghpull:`12510`
417
418
418 - Minimum jedi version is now 0.16. :ghpull:`12488`
419 - Minimum jedi version is now 0.16. :ghpull:`12488`
419
420
420
421
421
422
422 .. _version 717:
423 .. _version 717:
423
424
424 IPython 7.17
425 IPython 7.17
425 ============
426 ============
426
427
427 IPython 7.17 brings a couple of new improvements to API and a couple of user
428 IPython 7.17 brings a couple of new improvements to API and a couple of user
428 facing changes to make the terminal experience more user friendly.
429 facing changes to make the terminal experience more user friendly.
429
430
430 :ghpull:`12407` introduces the ability to pass extra argument to the IPython
431 :ghpull:`12407` introduces the ability to pass extra argument to the IPython
431 debugger class; this is to help a new project from ``kmaork``
432 debugger class; this is to help a new project from ``kmaork``
432 (https://github.com/kmaork/madbg) to feature a fully remote debugger.
433 (https://github.com/kmaork/madbg) to feature a fully remote debugger.
433
434
434 :ghpull:`12410` finally remove support for 3.6, while the codebase is still
435 :ghpull:`12410` finally remove support for 3.6, while the codebase is still
435 technically compatible; IPython will not install on Python 3.6.
436 technically compatible; IPython will not install on Python 3.6.
436
437
437 lots of work on the debugger and hidden frames from ``@impact27`` in
438 lots of work on the debugger and hidden frames from ``@impact27`` in
438 :ghpull:`12437`, :ghpull:`12445`, :ghpull:`12460` and in particular
439 :ghpull:`12437`, :ghpull:`12445`, :ghpull:`12460` and in particular
439 :ghpull:`12453` which make the debug magic more robust at handling spaces.
440 :ghpull:`12453` which make the debug magic more robust at handling spaces.
440
441
441 Biggest API addition is code transformation which is done before code execution;
442 Biggest API addition is code transformation which is done before code execution;
442 IPython allows a number of hooks to catch non-valid Python syntax (magic, prompt
443 IPython allows a number of hooks to catch non-valid Python syntax (magic, prompt
443 stripping...etc). Transformers are usually called many time; typically:
444 stripping...etc). Transformers are usually called many time; typically:
444
445
445 - When trying to figure out whether the code is complete and valid (should we
446 - When trying to figure out whether the code is complete and valid (should we
446 insert a new line or execute ?)
447 insert a new line or execute ?)
447 - During actual code execution pass before giving the code to Python's
448 - During actual code execution pass before giving the code to Python's
448 ``exec``.
449 ``exec``.
449
450
450 This lead to issues when transformer might have had side effects; or do external
451 This lead to issues when transformer might have had side effects; or do external
451 queries. Starting with IPython 7.17 you can expect your transformer to be called
452 queries. Starting with IPython 7.17 you can expect your transformer to be called
452 less time.
453 less time.
453
454
454 Input transformers are now called only once in the execution path of
455 Input transformers are now called only once in the execution path of
455 `InteractiveShell`, allowing to register transformer that potentially have side
456 `InteractiveShell`, allowing to register transformer that potentially have side
456 effects (note that this is not recommended). Internal methods `should_run_async`, and
457 effects (note that this is not recommended). Internal methods `should_run_async`, and
457 `run_cell_async` now take a recommended optional `transformed_cell`, and
458 `run_cell_async` now take a recommended optional `transformed_cell`, and
458 `preprocessing_exc_tuple` parameters that will become mandatory at some point in
459 `preprocessing_exc_tuple` parameters that will become mandatory at some point in
459 the future; that is to say cells need to be explicitly transformed to be valid
460 the future; that is to say cells need to be explicitly transformed to be valid
460 Python syntax ahead of trying to run them. :ghpull:`12440`;
461 Python syntax ahead of trying to run them. :ghpull:`12440`;
461
462
462 ``input_transformers`` can now also have an attribute ``has_side_effects`` set
463 ``input_transformers`` can now also have an attribute ``has_side_effects`` set
463 to `True`, when this attribute is present; this will prevent the transformers
464 to `True`, when this attribute is present; this will prevent the transformers
464 from being ran when IPython is trying to guess whether the user input is
465 from being ran when IPython is trying to guess whether the user input is
465 complete. Note that this may means you will need to explicitly execute in some
466 complete. Note that this may means you will need to explicitly execute in some
466 case where your transformations are now not ran; but will not affect users with
467 case where your transformations are now not ran; but will not affect users with
467 no custom extensions.
468 no custom extensions.
468
469
469
470
470 API Changes
471 API Changes
471 -----------
472 -----------
472
473
473 Change of API and exposed objects automatically detected using `frappuccino
474 Change of API and exposed objects automatically detected using `frappuccino
474 <https://pypi.org/project/frappuccino/>`_
475 <https://pypi.org/project/frappuccino/>`_
475
476
476
477
477 The following items are new since 7.16.0::
478 The following items are new since 7.16.0::
478
479
479 + IPython.core.interactiveshell.InteractiveShell.get_local_scope(self, stack_depth)
480 + IPython.core.interactiveshell.InteractiveShell.get_local_scope(self, stack_depth)
480
481
481 The following signatures differ since 7.16.0::
482 The following signatures differ since 7.16.0::
482
483
483 - IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True)
484 - IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True)
484 + 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)
485 + 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)
485
486
486 - IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell)
487 - IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell)
487 + IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell, *, transformed_cell=None, preprocessing_exc_tuple=None)
488 + IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell, *, transformed_cell=None, preprocessing_exc_tuple=None)
488
489
489 - IPython.terminal.debugger.TerminalPdb.pt_init(self)
490 - IPython.terminal.debugger.TerminalPdb.pt_init(self)
490 + IPython.terminal.debugger.TerminalPdb.pt_init(self, pt_session_options=None)
491 + IPython.terminal.debugger.TerminalPdb.pt_init(self, pt_session_options=None)
491
492
492 This method was added::
493 This method was added::
493
494
494 + IPython.core.interactiveshell.InteractiveShell.get_local_scope
495 + IPython.core.interactiveshell.InteractiveShell.get_local_scope
495
496
496 Which is now also present on subclasses::
497 Which is now also present on subclasses::
497
498
498 + IPython.terminal.embed.InteractiveShellEmbed.get_local_scope
499 + IPython.terminal.embed.InteractiveShellEmbed.get_local_scope
499 + IPython.terminal.interactiveshell.TerminalInteractiveShell.get_local_scope
500 + IPython.terminal.interactiveshell.TerminalInteractiveShell.get_local_scope
500
501
501
502
502 .. _version 716:
503 .. _version 716:
503
504
504 IPython 7.16
505 IPython 7.16
505 ============
506 ============
506
507
507
508
508 The default traceback mode will now skip frames that are marked with
509 The default traceback mode will now skip frames that are marked with
509 ``__tracebackhide__ = True`` and show how many traceback frames have been
510 ``__tracebackhide__ = True`` and show how many traceback frames have been
510 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
511 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
511 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
512 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
512
513
513 The ipython debugger also now understands ``__tracebackhide__`` as well and will
514 The ipython debugger also now understands ``__tracebackhide__`` as well and will
514 skip hidden frames when displaying. Movement up and down the stack will skip the
515 skip hidden frames when displaying. Movement up and down the stack will skip the
515 hidden frames and will show how many frames were hidden. Internal IPython frames
516 hidden frames and will show how many frames were hidden. Internal IPython frames
516 are also now hidden by default. The behavior can be changed with the
517 are also now hidden by default. The behavior can be changed with the
517 ``skip_hidden`` while in the debugger, command and accepts "yes", "no", "true"
518 ``skip_hidden`` while in the debugger, command and accepts "yes", "no", "true"
518 and "false" case insensitive parameters.
519 and "false" case insensitive parameters.
519
520
520
521
521 Misc Noticeable changes:
522 Misc Noticeable changes:
522 ------------------------
523 ------------------------
523
524
524 - Exceptions are now (re)raised when running notebooks via the :magic:`%run`, helping to catch issues in workflows and
525 - Exceptions are now (re)raised when running notebooks via the :magic:`%run`, helping to catch issues in workflows and
525 pipelines. :ghpull:`12301`
526 pipelines. :ghpull:`12301`
526 - Fix inputhook for qt 5.15.0 :ghpull:`12355`
527 - Fix inputhook for qt 5.15.0 :ghpull:`12355`
527 - Fix wx inputhook :ghpull:`12375`
528 - Fix wx inputhook :ghpull:`12375`
528 - Add handling for malformed pathext env var (Windows) :ghpull:`12367`
529 - Add handling for malformed pathext env var (Windows) :ghpull:`12367`
529 - use $SHELL in system_piped :ghpull:`12360` for uniform behavior with
530 - use $SHELL in system_piped :ghpull:`12360` for uniform behavior with
530 ipykernel.
531 ipykernel.
531
532
532 Reproducible Build
533 Reproducible Build
533 ------------------
534 ------------------
534
535
535 IPython 7.15 reproducible build did not work, so we try again this month
536 IPython 7.15 reproducible build did not work, so we try again this month
536 :ghpull:`12358`.
537 :ghpull:`12358`.
537
538
538
539
539 API Changes
540 API Changes
540 -----------
541 -----------
541
542
542 Change of API and exposed objects automatically detected using `frappuccino
543 Change of API and exposed objects automatically detected using `frappuccino
543 <https://pypi.org/project/frappuccino/>`_ (still in beta):
544 <https://pypi.org/project/frappuccino/>`_ (still in beta):
544
545
545
546
546 The following items are new and mostly related to understanding ``__tracebackbide__``::
547 The following items are new and mostly related to understanding ``__tracebackhide__``::
547
548
548 + IPython.core.debugger.Pdb.do_down(self, arg)
549 + IPython.core.debugger.Pdb.do_down(self, arg)
549 + IPython.core.debugger.Pdb.do_skip_hidden(self, arg)
550 + IPython.core.debugger.Pdb.do_skip_hidden(self, arg)
550 + IPython.core.debugger.Pdb.do_up(self, arg)
551 + IPython.core.debugger.Pdb.do_up(self, arg)
551 + IPython.core.debugger.Pdb.hidden_frames(self, stack)
552 + IPython.core.debugger.Pdb.hidden_frames(self, stack)
552 + IPython.core.debugger.Pdb.stop_here(self, frame)
553 + IPython.core.debugger.Pdb.stop_here(self, frame)
553
554
554
555
555 The following items have been removed::
556 The following items have been removed::
556
557
557 - IPython.core.debugger.Pdb.new_do_down
558 - IPython.core.debugger.Pdb.new_do_down
558 - IPython.core.debugger.Pdb.new_do_up
559 - IPython.core.debugger.Pdb.new_do_up
559
560
560 Those were implementation details.
561 Those were implementation details.
561
562
562
563
563 .. _version 715:
564 .. _version 715:
564
565
565 IPython 7.15
566 IPython 7.15
566 ============
567 ============
567
568
568 IPython 7.15 brings a number of bug fixes and user facing improvements.
569 IPython 7.15 brings a number of bug fixes and user facing improvements.
569
570
570 Misc Noticeable changes:
571 Misc Noticeable changes:
571 ------------------------
572 ------------------------
572
573
573 - Long completion name have better elision in terminal :ghpull:`12284`
574 - Long completion name have better elision in terminal :ghpull:`12284`
574 - I've started to test on Python 3.9 :ghpull:`12307` and fix some errors.
575 - I've started to test on Python 3.9 :ghpull:`12307` and fix some errors.
575 - Hi DPI scaling of figures when using qt eventloop :ghpull:`12314`
576 - Hi DPI scaling of figures when using qt eventloop :ghpull:`12314`
576 - Document the ability to have systemwide configuration for IPython.
577 - Document the ability to have systemwide configuration for IPython.
577 :ghpull:`12328`
578 :ghpull:`12328`
578 - Fix issues with input autoformatting :ghpull:`12336`
579 - Fix issues with input autoformatting :ghpull:`12336`
579 - ``IPython.core.debugger.Pdb`` is now interruptible (:ghpull:`12168`, in 7.14
580 - ``IPython.core.debugger.Pdb`` is now interruptible (:ghpull:`12168`, in 7.14
580 but forgotten in release notes)
581 but forgotten in release notes)
581 - Video HTML attributes (:ghpull:`12212`, in 7.14 but forgotten in release
582 - Video HTML attributes (:ghpull:`12212`, in 7.14 but forgotten in release
582 notes)
583 notes)
583
584
584 Reproducible Build
585 Reproducible Build
585 ------------------
586 ------------------
586
587
587 Starting with IPython 7.15, I am attempting to provide reproducible builds,
588 Starting with IPython 7.15, I am attempting to provide reproducible builds,
588 that is to say you should be able from the source tree to generate an sdist
589 that is to say you should be able from the source tree to generate an sdist
589 and wheel that are identical byte for byte with the publish version on PyPI.
590 and wheel that are identical byte for byte with the publish version on PyPI.
590
591
591 I've only tested on a couple of machines so far and the process is relatively
592 I've only tested on a couple of machines so far and the process is relatively
592 straightforward, so this mean that IPython not only have a deterministic build
593 straightforward, so this mean that IPython not only have a deterministic build
593 process, but also I have either removed, or put under control all effects of
594 process, but also I have either removed, or put under control all effects of
594 the build environments on the final artifact. I encourage you to attempt the
595 the build environments on the final artifact. I encourage you to attempt the
595 build process on your machine as documented in :ref:`core_developer_guide`
596 build process on your machine as documented in :ref:`core_developer_guide`
596 and let me know if you do not obtain an identical artifact.
597 and let me know if you do not obtain an identical artifact.
597
598
598 While reproducible builds is critical to check that the supply chain of (open
599 While reproducible builds is critical to check that the supply chain of (open
599 source) software has not been compromised, it can also help to speedup many
600 source) software has not been compromised, it can also help to speedup many
600 of the build processes in large environment (conda, apt...) by allowing
601 of the build processes in large environment (conda, apt...) by allowing
601 better caching of intermediate build steps.
602 better caching of intermediate build steps.
602
603
603 Learn more on `<https://reproducible-builds.org/>`_. `Reflections on trusting
604 Learn more on `<https://reproducible-builds.org/>`_. `Reflections on trusting
604 trust <https://dl.acm.org/doi/10.1145/358198.358210>`_ is also one of the
605 trust <https://dl.acm.org/doi/10.1145/358198.358210>`_ is also one of the
605 cornerstone and recommended reads on this subject.
606 cornerstone and recommended reads on this subject.
606
607
607 .. note::
608 .. note::
608
609
609 The build commit from which the sdist is generated is also `signed
610 The build commit from which the sdist is generated is also `signed
610 <https://en.wikipedia.org/wiki/Digital_signature>`_, so you should be able to
611 <https://en.wikipedia.org/wiki/Digital_signature>`_, so you should be able to
611 check it has not been compromised, and the git repository is a `merkle-tree
612 check it has not been compromised, and the git repository is a `merkle-tree
612 <https://en.wikipedia.org/wiki/Merkle_tree>`_, you can check the consistency
613 <https://en.wikipedia.org/wiki/Merkle_tree>`_, you can check the consistency
613 with `git-fsck <https://git-scm.com/docs/git-fsck>`_ which you likely `want
614 with `git-fsck <https://git-scm.com/docs/git-fsck>`_ which you likely `want
614 to enable by default
615 to enable by default
615 <https://gist.github.com/mbbx6spp/14b86437e794bffb4120>`_.
616 <https://gist.github.com/mbbx6spp/14b86437e794bffb4120>`_.
616
617
617 NEP29: Last version to support Python 3.6
618 NEP29: Last version to support Python 3.6
618 -----------------------------------------
619 -----------------------------------------
619
620
620 IPython 7.15 will be the Last IPython version to officially support Python
621 IPython 7.15 will be the Last IPython version to officially support Python
621 3.6, as stated by `NumPy Enhancement Proposal 29
622 3.6, as stated by `NumPy Enhancement Proposal 29
622 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_. Starting with
623 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_. Starting with
623 next minor version of IPython I may stop testing on Python 3.6 and may stop
624 next minor version of IPython I may stop testing on Python 3.6 and may stop
624 publishing release artifacts that install on Python 3.6
625 publishing release artifacts that install on Python 3.6
625
626
626 Highlighted features
627 Highlighted features
627 --------------------
628 --------------------
628
629
629 Highlighted features are not new, but seem to not be widely known, this
630 Highlighted features are not new, but seem to not be widely known, this
630 section will help you discover in more narrative form what you can do with
631 section will help you discover in more narrative form what you can do with
631 IPython.
632 IPython.
632
633
633 Increase Tab Completion Menu Height
634 Increase Tab Completion Menu Height
634 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
635 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
635
636
636 In terminal IPython it is possible to increase the hight of the tab-completion
637 In terminal IPython it is possible to increase the hight of the tab-completion
637 menu. To do so set the value of
638 menu. To do so set the value of
638 :configtrait:`TerminalInteractiveShell.space_for_menu`, this will reserve more
639 :configtrait:`TerminalInteractiveShell.space_for_menu`, this will reserve more
639 space at the bottom of the screen for various kind of menus in IPython including
640 space at the bottom of the screen for various kind of menus in IPython including
640 tab completion and searching in history.
641 tab completion and searching in history.
641
642
642 Autoformat Code in the terminal
643 Autoformat Code in the terminal
643 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
644 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
644
645
645 If you have a preferred code formatter, you can configure IPython to
646 If you have a preferred code formatter, you can configure IPython to
646 reformat your code. Set the value of
647 reformat your code. Set the value of
647 :configtrait:`TerminalInteractiveShell.autoformatter` to for example ``'black'``
648 :configtrait:`TerminalInteractiveShell.autoformatter` to for example ``'black'``
648 and IPython will auto format your code when possible.
649 and IPython will auto format your code when possible.
649
650
650
651
651 .. _version 714:
652 .. _version 714:
652
653
653 IPython 7.14
654 IPython 7.14
654 ============
655 ============
655
656
656 IPython 7.14 is a minor release that fix a couple of bugs and prepare
657 IPython 7.14 is a minor release that fix a couple of bugs and prepare
657 compatibility with new or future versions of some libraries.
658 compatibility with new or future versions of some libraries.
658
659
659 Important changes:
660 Important changes:
660 ------------------
661 ------------------
661
662
662 - Fix compatibility with Sphinx 3+ :ghpull:`12235`
663 - Fix compatibility with Sphinx 3+ :ghpull:`12235`
663 - Remove deprecated matplotlib parameter usage, compatibility with matplotlib
664 - Remove deprecated matplotlib parameter usage, compatibility with matplotlib
664 3.3+ :`122250`
665 3.3+ :`122250`
665
666
666 Misc Changes
667 Misc Changes
667 ------------
668 ------------
668
669
669 - set ``.py`` extension when editing current buffer in vi/emacs. :ghpull:`12167`
670 - set ``.py`` extension when editing current buffer in vi/emacs. :ghpull:`12167`
670 - support for unicode identifiers in ``?``/``??`` :ghpull:`12208`
671 - support for unicode identifiers in ``?``/``??`` :ghpull:`12208`
671 - add extra options to the ``Video`` Rich objects :ghpull:`12212`
672 - add extra options to the ``Video`` Rich objects :ghpull:`12212`
672 - add pretty-printing to ``SimpleNamespace`` :ghpull:`12230`
673 - add pretty-printing to ``SimpleNamespace`` :ghpull:`12230`
673
674
674 IPython.core.debugger.Pdb is now interruptible
675 IPython.core.debugger.Pdb is now interruptible
675 ----------------------------------------------
676 ----------------------------------------------
676
677
677 A ``KeyboardInterrupt`` will now interrupt IPython's extended debugger, in order to make Jupyter able to interrupt it. (:ghpull:`12168`)
678 A ``KeyboardInterrupt`` will now interrupt IPython's extended debugger, in order to make Jupyter able to interrupt it. (:ghpull:`12168`)
678
679
679 Video HTML attributes
680 Video HTML attributes
680 ---------------------
681 ---------------------
681
682
682 Add an option to `IPython.display.Video` to change the attributes of the HTML display of the video (:ghpull:`12212`)
683 Add an option to `IPython.display.Video` to change the attributes of the HTML display of the video (:ghpull:`12212`)
683
684
684
685
685 Pending deprecated imports
686 Pending deprecated imports
686 --------------------------
687 --------------------------
687
688
688 Many object present in ``IPython.core.display`` are there for internal use only,
689 Many object present in ``IPython.core.display`` are there for internal use only,
689 and should already been imported from ``IPython.display`` by users and external
690 and should already been imported from ``IPython.display`` by users and external
690 libraries. Trying to import those from ``IPython.core.display`` is still possible
691 libraries. Trying to import those from ``IPython.core.display`` is still possible
691 but will trigger a
692 but will trigger a
692 deprecation warning in later versions of IPython and will become errors in the
693 deprecation warning in later versions of IPython and will become errors in the
693 future.
694 future.
694
695
695 This will simplify compatibility with other Python kernels (like Xeus-Python),
696 This will simplify compatibility with other Python kernels (like Xeus-Python),
696 and simplify code base.
697 and simplify code base.
697
698
698
699
699
700
700
701
701 .. _version 713:
702 .. _version 713:
702
703
703 IPython 7.13
704 IPython 7.13
704 ============
705 ============
705
706
706 IPython 7.13 is the final release of the 7.x branch since master is diverging
707 IPython 7.13 is the final release of the 7.x branch since master is diverging
707 toward an 8.0. Exiting new features have already been merged in 8.0 and will
708 toward an 8.0. Exiting new features have already been merged in 8.0 and will
708 not be available on the 7.x branch. All the changes below have been backported
709 not be available on the 7.x branch. All the changes below have been backported
709 from the master branch.
710 from the master branch.
710
711
711
712
712 - Fix inability to run PDB when inside an event loop :ghpull:`12141`
713 - Fix inability to run PDB when inside an event loop :ghpull:`12141`
713 - Fix ability to interrupt some processes on windows :ghpull:`12137`
714 - Fix ability to interrupt some processes on windows :ghpull:`12137`
714 - Fix debugger shortcuts :ghpull:`12132`
715 - Fix debugger shortcuts :ghpull:`12132`
715 - improve tab completion when inside a string by removing irrelevant elements :ghpull:`12128`
716 - improve tab completion when inside a string by removing irrelevant elements :ghpull:`12128`
716 - Fix display of filename tab completion when the path is long :ghpull:`12122`
717 - Fix display of filename tab completion when the path is long :ghpull:`12122`
717 - Many removal of Python 2 specific code path :ghpull:`12110`
718 - Many removal of Python 2 specific code path :ghpull:`12110`
718 - displaying wav files do not require NumPy anymore, and is 5x to 30x faster :ghpull:`12113`
719 - displaying wav files do not require NumPy anymore, and is 5x to 30x faster :ghpull:`12113`
719
720
720 See the list of all closed issues and pull request on `github
721 See the list of all closed issues and pull request on `github
721 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A7.13>`_.
722 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A7.13>`_.
722
723
723 .. _version 712:
724 .. _version 712:
724
725
725 IPython 7.12
726 IPython 7.12
726 ============
727 ============
727
728
728 IPython 7.12 is a minor update that mostly brings code cleanup, removal of
729 IPython 7.12 is a minor update that mostly brings code cleanup, removal of
729 longtime deprecated function and a couple update to documentation cleanup as well.
730 longtime deprecated function and a couple update to documentation cleanup as well.
730
731
731 Notable changes are the following:
732 Notable changes are the following:
732
733
733 - Exit non-zero when ipython is given a file path to run that doesn't exist :ghpull:`12074`
734 - Exit non-zero when ipython is given a file path to run that doesn't exist :ghpull:`12074`
734 - Test PR on ARM64 with Travis-CI :ghpull:`12073`
735 - Test PR on ARM64 with Travis-CI :ghpull:`12073`
735 - Update CI to work with latest Pytest :ghpull:`12086`
736 - Update CI to work with latest Pytest :ghpull:`12086`
736 - Add infrastructure to run ipykernel eventloop via trio :ghpull:`12097`
737 - Add infrastructure to run ipykernel eventloop via trio :ghpull:`12097`
737 - Support git blame ignore revs :ghpull:`12091`
738 - Support git blame ignore revs :ghpull:`12091`
738 - Start multi-line ``__repr__`` s on their own line :ghpull:`12099`
739 - Start multi-line ``__repr__`` s on their own line :ghpull:`12099`
739
740
740 .. _version 7111:
741 .. _version 7111:
741
742
742 IPython 7.11.1
743 IPython 7.11.1
743 ==============
744 ==============
744
745
745 A couple of deprecated functions (no-op) have been reintroduces in py3compat as
746 A couple of deprecated functions (no-op) have been reintroduces in py3compat as
746 Cython was still relying on them, and will be removed in a couple of versions.
747 Cython was still relying on them, and will be removed in a couple of versions.
747
748
748 .. _version 711:
749 .. _version 711:
749
750
750 IPython 7.11
751 IPython 7.11
751 ============
752 ============
752
753
753 IPython 7.11 received a couple of compatibility fixes and code cleanup.
754 IPython 7.11 received a couple of compatibility fixes and code cleanup.
754
755
755 A number of function in the ``py3compat`` have been removed; a number of types
756 A number of function in the ``py3compat`` have been removed; a number of types
756 in the IPython code base are now non-ambiguous and now always ``unicode``
757 in the IPython code base are now non-ambiguous and now always ``unicode``
757 instead of ``Union[Unicode,bytes]``; many of the relevant code path have thus
758 instead of ``Union[Unicode,bytes]``; many of the relevant code path have thus
758 been simplified/cleaned and types annotation added.
759 been simplified/cleaned and types annotation added.
759
760
760 IPython support several verbosity level from exceptions. ``xmode plain`` now
761 IPython support several verbosity level from exceptions. ``xmode plain`` now
761 support chained exceptions. :ghpull:`11999`
762 support chained exceptions. :ghpull:`11999`
762
763
763 We are starting to remove ``shell=True`` in some usages of subprocess. While not directly
764 We are starting to remove ``shell=True`` in some usages of subprocess. While not directly
764 a security issue (as IPython is made to run arbitrary code anyway) it is not good
765 a security issue (as IPython is made to run arbitrary code anyway) it is not good
765 practice and we'd like to show the example. :ghissue:`12023`. This discussion
766 practice and we'd like to show the example. :ghissue:`12023`. This discussion
766 was started by ``@mschwager`` thanks to a new auditing tool they are working on
767 was started by ``@mschwager`` thanks to a new auditing tool they are working on
767 with duo-labs (`dlint <https://github.com/duo-labs/dlint>`_).
768 with duo-labs (`dlint <https://github.com/duo-labs/dlint>`_).
768
769
769 Work around some bugs in Python 3.9 tokenizer :ghpull:`12057`
770 Work around some bugs in Python 3.9 tokenizer :ghpull:`12057`
770
771
771 IPython will now print its version after a crash. :ghpull:`11986`
772 IPython will now print its version after a crash. :ghpull:`11986`
772
773
773 This is likely the last release from the 7.x series that will see new feature.
774 This is likely the last release from the 7.x series that will see new feature.
774 The master branch will soon accept large code changes and thrilling new
775 The master branch will soon accept large code changes and thrilling new
775 features; the 7.x branch will only start to accept critical bug fixes, and
776 features; the 7.x branch will only start to accept critical bug fixes, and
776 update dependencies.
777 update dependencies.
777
778
778 .. _version 7102:
779 .. _version 7102:
779
780
780 IPython 7.10.2
781 IPython 7.10.2
781 ==============
782 ==============
782
783
783 IPython 7.10.2 fix a couple of extra incompatibility between IPython, ipdb,
784 IPython 7.10.2 fix a couple of extra incompatibility between IPython, ipdb,
784 asyncio and Prompt Toolkit 3.
785 asyncio and Prompt Toolkit 3.
785
786
786 .. _version 7101:
787 .. _version 7101:
787
788
788 IPython 7.10.1
789 IPython 7.10.1
789 ==============
790 ==============
790
791
791 IPython 7.10.1 fix a couple of incompatibilities with Prompt toolkit 3 (please
792 IPython 7.10.1 fix a couple of incompatibilities with Prompt toolkit 3 (please
792 update Prompt toolkit to 3.0.2 at least), and fixes some interaction with
793 update Prompt toolkit to 3.0.2 at least), and fixes some interaction with
793 headless IPython.
794 headless IPython.
794
795
795 .. _version 7100:
796 .. _version 7100:
796
797
797 IPython 7.10.0
798 IPython 7.10.0
798 ==============
799 ==============
799
800
800 IPython 7.10 is the first double digit minor release in the last decade, and
801 IPython 7.10 is the first double digit minor release in the last decade, and
801 first since the release of IPython 1.0, previous double digit minor release was
802 first since the release of IPython 1.0, previous double digit minor release was
802 in August 2009.
803 in August 2009.
803
804
804 We've been trying to give you regular release on the last Friday of every month
805 We've been trying to give you regular release on the last Friday of every month
805 for a guaranty of rapid access to bug fixes and new features.
806 for a guaranty of rapid access to bug fixes and new features.
806
807
807 Unlike the previous first few releases that have seen only a couple of code
808 Unlike the previous first few releases that have seen only a couple of code
808 changes, 7.10 bring a number of changes, new features and bugfixes.
809 changes, 7.10 bring a number of changes, new features and bugfixes.
809
810
810 Stop Support for Python 3.5 – Adopt NEP 29
811 Stop Support for Python 3.5 – Adopt NEP 29
811 ------------------------------------------
812 ------------------------------------------
812
813
813 IPython has decided to follow the informational `NEP 29
814 IPython has decided to follow the informational `NEP 29
814 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_ which layout a clear
815 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_ which layout a clear
815 policy as to which version of (C)Python and NumPy are supported.
816 policy as to which version of (C)Python and NumPy are supported.
816
817
817 We thus dropped support for Python 3.5, and cleaned up a number of code path
818 We thus dropped support for Python 3.5, and cleaned up a number of code path
818 that were Python-version dependant. If you are on 3.5 or earlier pip should
819 that were Python-version dependant. If you are on 3.5 or earlier pip should
819 automatically give you the latest compatible version of IPython so you do not
820 automatically give you the latest compatible version of IPython so you do not
820 need to pin to a given version.
821 need to pin to a given version.
821
822
822 Support for Prompt Toolkit 3.0
823 Support for Prompt Toolkit 3.0
823 ------------------------------
824 ------------------------------
824
825
825 Prompt Toolkit 3.0 was release a week before IPython 7.10 and introduces a few
826 Prompt Toolkit 3.0 was release a week before IPython 7.10 and introduces a few
826 breaking changes. We believe IPython 7.10 should be compatible with both Prompt
827 breaking changes. We believe IPython 7.10 should be compatible with both Prompt
827 Toolkit 2.x and 3.x, though it has not been extensively tested with 3.x so
828 Toolkit 2.x and 3.x, though it has not been extensively tested with 3.x so
828 please report any issues.
829 please report any issues.
829
830
830
831
831 Prompt Rendering Performance improvements
832 Prompt Rendering Performance improvements
832 -----------------------------------------
833 -----------------------------------------
833
834
834 Pull Request :ghpull:`11933` introduced an optimisation in the prompt rendering
835 Pull Request :ghpull:`11933` introduced an optimisation in the prompt rendering
835 logic that should decrease the resource usage of IPython when using the
836 logic that should decrease the resource usage of IPython when using the
836 _default_ configuration but could potentially introduce a regression of
837 _default_ configuration but could potentially introduce a regression of
837 functionalities if you are using a custom prompt.
838 functionalities if you are using a custom prompt.
838
839
839 We know assume if you haven't changed the default keybindings that the prompt
840 We know assume if you haven't changed the default keybindings that the prompt
840 **will not change** during the duration of your input – which is for example
841 **will not change** during the duration of your input – which is for example
841 not true when using vi insert mode that switches between `[ins]` and `[nor]`
842 not true when using vi insert mode that switches between `[ins]` and `[nor]`
842 for the current mode.
843 for the current mode.
843
844
844 If you are experiencing any issue let us know.
845 If you are experiencing any issue let us know.
845
846
846 Code autoformatting
847 Code autoformatting
847 -------------------
848 -------------------
848
849
849 The IPython terminal can now auto format your code just before entering a new
850 The IPython terminal can now auto format your code just before entering a new
850 line or executing a command. To do so use the
851 line or executing a command. To do so use the
851 ``--TerminalInteractiveShell.autoformatter`` option and set it to ``'black'``;
852 ``--TerminalInteractiveShell.autoformatter`` option and set it to ``'black'``;
852 if black is installed IPython will use black to format your code when possible.
853 if black is installed IPython will use black to format your code when possible.
853
854
854 IPython cannot always properly format your code; in particular it will
855 IPython cannot always properly format your code; in particular it will
855 auto formatting with *black* will only work if:
856 auto formatting with *black* will only work if:
856
857
857 - Your code does not contains magics or special python syntax.
858 - Your code does not contains magics or special python syntax.
858
859
859 - There is no code after your cursor.
860 - There is no code after your cursor.
860
861
861 The Black API is also still in motion; so this may not work with all versions of
862 The Black API is also still in motion; so this may not work with all versions of
862 black.
863 black.
863
864
864 It should be possible to register custom formatter, though the API is till in
865 It should be possible to register custom formatter, though the API is till in
865 flux.
866 flux.
866
867
867 Arbitrary Mimetypes Handing in Terminal (Aka inline images in terminal)
868 Arbitrary Mimetypes Handing in Terminal (Aka inline images in terminal)
868 -----------------------------------------------------------------------
869 -----------------------------------------------------------------------
869
870
870 When using IPython terminal it is now possible to register function to handle
871 When using IPython terminal it is now possible to register function to handle
871 arbitrary mimetypes. While rendering non-text based representation was possible in
872 arbitrary mimetypes. While rendering non-text based representation was possible in
872 many jupyter frontend; it was not possible in terminal IPython, as usually
873 many jupyter frontend; it was not possible in terminal IPython, as usually
873 terminal are limited to displaying text. As many terminal these days provide
874 terminal are limited to displaying text. As many terminal these days provide
874 escape sequences to display non-text; bringing this loved feature to IPython CLI
875 escape sequences to display non-text; bringing this loved feature to IPython CLI
875 made a lot of sens. This functionality will not only allow inline images; but
876 made a lot of sens. This functionality will not only allow inline images; but
876 allow opening of external program; for example ``mplayer`` to "display" sound
877 allow opening of external program; for example ``mplayer`` to "display" sound
877 files.
878 files.
878
879
879 So far only the hooks necessary for this are in place, but no default mime
880 So far only the hooks necessary for this are in place, but no default mime
880 renderers added; so inline images will only be available via extensions. We will
881 renderers added; so inline images will only be available via extensions. We will
881 progressively enable these features by default in the next few releases, and
882 progressively enable these features by default in the next few releases, and
882 contribution is welcomed.
883 contribution is welcomed.
883
884
884 We welcome any feedback on the API. See :ref:`shell_mimerenderer` for more
885 We welcome any feedback on the API. See :ref:`shell_mimerenderer` for more
885 informations.
886 informations.
886
887
887 This is originally based on work form in :ghpull:`10610` from @stephanh42
888 This is originally based on work form in :ghpull:`10610` from @stephanh42
888 started over two years ago, and still a lot need to be done.
889 started over two years ago, and still a lot need to be done.
889
890
890 MISC
891 MISC
891 ----
892 ----
892
893
893 - Completions can define their own ordering :ghpull:`11855`
894 - Completions can define their own ordering :ghpull:`11855`
894 - Enable Plotting in the same cell than the one that import matplotlib
895 - Enable Plotting in the same cell than the one that import matplotlib
895 :ghpull:`11916`
896 :ghpull:`11916`
896 - Allow to store and restore multiple variables at once :ghpull:`11930`
897 - Allow to store and restore multiple variables at once :ghpull:`11930`
897
898
898 You can see `all pull-requests <https://github.com/ipython/ipython/pulls?q=is%3Apr+milestone%3A7.10+is%3Aclosed>`_ for this release.
899 You can see `all pull-requests <https://github.com/ipython/ipython/pulls?q=is%3Apr+milestone%3A7.10+is%3Aclosed>`_ for this release.
899
900
900 API Changes
901 API Changes
901 -----------
902 -----------
902
903
903 Change of API and exposed objects automatically detected using `frappuccino <https://pypi.org/project/frappuccino/>`_ (still in beta):
904 Change of API and exposed objects automatically detected using `frappuccino <https://pypi.org/project/frappuccino/>`_ (still in beta):
904
905
905 The following items are new in IPython 7.10::
906 The following items are new in IPython 7.10::
906
907
907 + IPython.terminal.shortcuts.reformat_text_before_cursor(buffer, document, shell)
908 + IPython.terminal.shortcuts.reformat_text_before_cursor(buffer, document, shell)
908 + IPython.terminal.interactiveshell.PTK3
909 + IPython.terminal.interactiveshell.PTK3
909 + IPython.terminal.interactiveshell.black_reformat_handler(text_before_cursor)
910 + IPython.terminal.interactiveshell.black_reformat_handler(text_before_cursor)
910 + IPython.terminal.prompts.RichPromptDisplayHook.write_format_data(self, format_dict, md_dict='None')
911 + IPython.terminal.prompts.RichPromptDisplayHook.write_format_data(self, format_dict, md_dict='None')
911
912
912 The following items have been removed in 7.10::
913 The following items have been removed in 7.10::
913
914
914 - IPython.lib.pretty.DICT_IS_ORDERED
915 - IPython.lib.pretty.DICT_IS_ORDERED
915
916
916 The following signatures differ between versions::
917 The following signatures differ between versions::
917
918
918 - IPython.extensions.storemagic.restore_aliases(ip)
919 - IPython.extensions.storemagic.restore_aliases(ip)
919 + IPython.extensions.storemagic.restore_aliases(ip, alias='None')
920 + IPython.extensions.storemagic.restore_aliases(ip, alias='None')
920
921
921 Special Thanks
922 Special Thanks
922 --------------
923 --------------
923
924
924 - @stephanh42 who started the work on inline images in terminal 2 years ago
925 - @stephanh42 who started the work on inline images in terminal 2 years ago
925 - @augustogoulart who spent a lot of time triaging issues and responding to
926 - @augustogoulart who spent a lot of time triaging issues and responding to
926 users.
927 users.
927 - @con-f-use who is my (@Carreau) first sponsor on GitHub, as a reminder if you
928 - @con-f-use who is my (@Carreau) first sponsor on GitHub, as a reminder if you
928 like IPython, Jupyter and many other library of the SciPy stack you can
929 like IPython, Jupyter and many other library of the SciPy stack you can
929 donate to numfocus.org non profit
930 donate to numfocus.org non profit
930
931
931 .. _version 790:
932 .. _version 790:
932
933
933 IPython 7.9.0
934 IPython 7.9.0
934 =============
935 =============
935
936
936 IPython 7.9 is a small release with a couple of improvement and bug fixes.
937 IPython 7.9 is a small release with a couple of improvement and bug fixes.
937
938
938 - Xterm terminal title should be restored on exit :ghpull:`11910`
939 - Xterm terminal title should be restored on exit :ghpull:`11910`
939 - special variables ``_``,``__``, ``___`` are not set anymore when cache size
940 - special variables ``_``,``__``, ``___`` are not set anymore when cache size
940 is 0 or less. :ghpull:`11877`
941 is 0 or less. :ghpull:`11877`
941 - Autoreload should have regained some speed by using a new heuristic logic to
942 - Autoreload should have regained some speed by using a new heuristic logic to
942 find all objects needing reload. This should avoid large objects traversal
943 find all objects needing reload. This should avoid large objects traversal
943 like pandas dataframes. :ghpull:`11876`
944 like pandas dataframes. :ghpull:`11876`
944 - Get ready for Python 4. :ghpull:`11874`
945 - Get ready for Python 4. :ghpull:`11874`
945 - `%env` Magic now has heuristic to hide potentially sensitive values :ghpull:`11896`
946 - `%env` Magic now has heuristic to hide potentially sensitive values :ghpull:`11896`
946
947
947 This is a small release despite a number of Pull Request Pending that need to
948 This is a small release despite a number of Pull Request Pending that need to
948 be reviewed/worked on. Many of the core developers have been busy outside of
949 be reviewed/worked on. Many of the core developers have been busy outside of
949 IPython/Jupyter and we thanks all contributor for their patience; we'll work on
950 IPython/Jupyter and we thanks all contributor for their patience; we'll work on
950 these as soon as we have time.
951 these as soon as we have time.
951
952
952
953
953 .. _version780:
954 .. _version780:
954
955
955 IPython 7.8.0
956 IPython 7.8.0
956 =============
957 =============
957
958
958 IPython 7.8.0 contain a few bugfix and 2 new APIs:
959 IPython 7.8.0 contain a few bugfix and 2 new APIs:
959
960
960 - Enable changing the font color for LaTeX rendering :ghpull:`11840`
961 - Enable changing the font color for LaTeX rendering :ghpull:`11840`
961 - and Re-Expose some PDB API (see below)
962 - and Re-Expose some PDB API (see below)
962
963
963 Expose Pdb API
964 Expose Pdb API
964 --------------
965 --------------
965
966
966 Expose the built-in ``pdb.Pdb`` API. ``Pdb`` constructor arguments are generically
967 Expose the built-in ``pdb.Pdb`` API. ``Pdb`` constructor arguments are generically
967 exposed, regardless of python version.
968 exposed, regardless of python version.
968 Newly exposed arguments:
969 Newly exposed arguments:
969
970
970 - ``skip`` - Python 3.1+
971 - ``skip`` - Python 3.1+
971 - ``nosiginnt`` - Python 3.2+
972 - ``nosiginnt`` - Python 3.2+
972 - ``readrc`` - Python 3.6+
973 - ``readrc`` - Python 3.6+
973
974
974 Try it out::
975 Try it out::
975
976
976 from IPython.terminal.debugger import TerminalPdb
977 from IPython.terminal.debugger import TerminalPdb
977 pdb = TerminalPdb(skip=["skipthismodule"])
978 pdb = TerminalPdb(skip=["skipthismodule"])
978
979
979
980
980 See :ghpull:`11840`
981 See :ghpull:`11840`
981
982
982 .. _version770:
983 .. _version770:
983
984
984 IPython 7.7.0
985 IPython 7.7.0
985 =============
986 =============
986
987
987 IPython 7.7.0 contain multiple bug fixes and documentation updates; Here are a
988 IPython 7.7.0 contain multiple bug fixes and documentation updates; Here are a
988 few of the outstanding issue fixed:
989 few of the outstanding issue fixed:
989
990
990 - Fix a bug introduced in 7.6 where the ``%matplotlib`` magic would fail on
991 - Fix a bug introduced in 7.6 where the ``%matplotlib`` magic would fail on
991 previously acceptable arguments :ghpull:`11814`.
992 previously acceptable arguments :ghpull:`11814`.
992 - Fix the manage location on freebsd :ghpull:`11808`.
993 - Fix the manage location on freebsd :ghpull:`11808`.
993 - Fix error message about aliases after ``%reset`` call in ipykernel
994 - Fix error message about aliases after ``%reset`` call in ipykernel
994 :ghpull:`11806`
995 :ghpull:`11806`
995 - Fix Duplication completions in emacs :ghpull:`11803`
996 - Fix Duplication completions in emacs :ghpull:`11803`
996
997
997 We are planning to adopt `NEP29 <https://github.com/numpy/numpy/pull/14086>`_
998 We are planning to adopt `NEP29 <https://github.com/numpy/numpy/pull/14086>`_
998 (still currently in draft) which may make this minor version of IPython the
999 (still currently in draft) which may make this minor version of IPython the
999 last one to support Python 3.5 and will make the code base more aggressive
1000 last one to support Python 3.5 and will make the code base more aggressive
1000 toward removing compatibility with older versions of Python.
1001 toward removing compatibility with older versions of Python.
1001
1002
1002 GitHub now support to give only "Triage" permissions to users; if you'd like to
1003 GitHub now support to give only "Triage" permissions to users; if you'd like to
1003 help close stale issues and labels issues please reach to us with your GitHub
1004 help close stale issues and labels issues please reach to us with your GitHub
1004 Username and we'll add you to the triage team. It is a great way to start
1005 Username and we'll add you to the triage team. It is a great way to start
1005 contributing and a path toward getting commit rights.
1006 contributing and a path toward getting commit rights.
1006
1007
1007 .. _version761:
1008 .. _version761:
1008
1009
1009 IPython 7.6.1
1010 IPython 7.6.1
1010 =============
1011 =============
1011
1012
1012 IPython 7.6.1 contain a critical bugfix in the ``%timeit`` magic, which would
1013 IPython 7.6.1 contain a critical bugfix in the ``%timeit`` magic, which would
1013 crash on some inputs as a side effect of :ghpull:`11716`. See :ghpull:`11812`
1014 crash on some inputs as a side effect of :ghpull:`11716`. See :ghpull:`11812`
1014
1015
1015
1016
1016 .. _whatsnew760:
1017 .. _whatsnew760:
1017
1018
1018 IPython 7.6.0
1019 IPython 7.6.0
1019 =============
1020 =============
1020
1021
1021 IPython 7.6.0 contains a couple of bug fixes and number of small features
1022 IPython 7.6.0 contains a couple of bug fixes and number of small features
1022 additions as well as some compatibility with the current development version of
1023 additions as well as some compatibility with the current development version of
1023 Python 3.8.
1024 Python 3.8.
1024
1025
1025 - Add a ``-l`` option to :magic:`psearch` to list the available search
1026 - Add a ``-l`` option to :magic:`psearch` to list the available search
1026 types. :ghpull:`11672`
1027 types. :ghpull:`11672`
1027 - Support ``PathLike`` for ``DisplayObject`` and ``Image``. :ghpull:`11764`
1028 - Support ``PathLike`` for ``DisplayObject`` and ``Image``. :ghpull:`11764`
1028 - Configurability of timeout in the test suite for slow platforms.
1029 - Configurability of timeout in the test suite for slow platforms.
1029 :ghpull:`11756`
1030 :ghpull:`11756`
1030 - Accept any casing for matplotlib backend. :ghpull:`121748`
1031 - Accept any casing for matplotlib backend. :ghpull:`121748`
1031 - Properly skip test that requires numpy to be installed :ghpull:`11723`
1032 - Properly skip test that requires numpy to be installed :ghpull:`11723`
1032 - More support for Python 3.8 and positional only arguments (pep570)
1033 - More support for Python 3.8 and positional only arguments (pep570)
1033 :ghpull:`11720`
1034 :ghpull:`11720`
1034 - Unicode names for the completion are loaded lazily on first use which
1035 - Unicode names for the completion are loaded lazily on first use which
1035 should decrease startup time. :ghpull:`11693`
1036 should decrease startup time. :ghpull:`11693`
1036 - Autoreload now update the types of reloaded objects; this for example allow
1037 - Autoreload now update the types of reloaded objects; this for example allow
1037 pickling of reloaded objects. :ghpull:`11644`
1038 pickling of reloaded objects. :ghpull:`11644`
1038 - Fix a bug where ``%%time`` magic would suppress cell output. :ghpull:`11716`
1039 - Fix a bug where ``%%time`` magic would suppress cell output. :ghpull:`11716`
1039
1040
1040
1041
1041 Prepare migration to pytest (instead of nose) for testing
1042 Prepare migration to pytest (instead of nose) for testing
1042 ---------------------------------------------------------
1043 ---------------------------------------------------------
1043
1044
1044 Most of the work between 7.5 and 7.6 was to prepare the migration from our
1045 Most of the work between 7.5 and 7.6 was to prepare the migration from our
1045 testing framework to pytest. Most of the test suite should now work by simply
1046 testing framework to pytest. Most of the test suite should now work by simply
1046 issuing ``pytest`` from the root of the repository.
1047 issuing ``pytest`` from the root of the repository.
1047
1048
1048 The migration to pytest is just at its beginning. Many of our test still rely
1049 The migration to pytest is just at its beginning. Many of our test still rely
1049 on IPython-specific plugins for nose using pytest (doctest using IPython syntax
1050 on IPython-specific plugins for nose using pytest (doctest using IPython syntax
1050 is one example of this where test appear as "passing", while no code has been
1051 is one example of this where test appear as "passing", while no code has been
1051 ran). Many test also need to be updated like ``yield-test`` to be properly
1052 ran). Many test also need to be updated like ``yield-test`` to be properly
1052 parametrized tests.
1053 parametrized tests.
1053
1054
1054 Migration to pytest allowed me to discover a number of issues in our test
1055 Migration to pytest allowed me to discover a number of issues in our test
1055 suite; which was hiding a number of subtle issues – or not actually running
1056 suite; which was hiding a number of subtle issues – or not actually running
1056 some of the tests in our test suite – I have thus corrected many of those; like
1057 some of the tests in our test suite – I have thus corrected many of those; like
1057 improperly closed resources; or used of deprecated features. I also made use of
1058 improperly closed resources; or used of deprecated features. I also made use of
1058 the ``pytest --durations=...`` to find some of our slowest test and speed them
1059 the ``pytest --durations=...`` to find some of our slowest test and speed them
1059 up (our test suite can now be up to 10% faster). Pytest as also a variety of
1060 up (our test suite can now be up to 10% faster). Pytest as also a variety of
1060 plugins and flags which will make the code quality of IPython and the testing
1061 plugins and flags which will make the code quality of IPython and the testing
1061 experience better.
1062 experience better.
1062
1063
1063 Misc
1064 Misc
1064 ----
1065 ----
1065
1066
1066 We skipped the release of 7.6 at the end of May, but will attempt to get back
1067 We skipped the release of 7.6 at the end of May, but will attempt to get back
1067 on schedule. We are starting to think about making introducing backward
1068 on schedule. We are starting to think about making introducing backward
1068 incompatible change and start the 8.0 series.
1069 incompatible change and start the 8.0 series.
1069
1070
1070 Special Thanks to Gabriel (@gpotter2 on GitHub), who among other took care many
1071 Special Thanks to Gabriel (@gpotter2 on GitHub), who among other took care many
1071 of the remaining task for 7.4 and 7.5, like updating the website.
1072 of the remaining task for 7.4 and 7.5, like updating the website.
1072
1073
1073 .. _whatsnew750:
1074 .. _whatsnew750:
1074
1075
1075 IPython 7.5.0
1076 IPython 7.5.0
1076 =============
1077 =============
1077
1078
1078 IPython 7.5.0 consist mostly of bug-fixes, and documentation updates, with one
1079 IPython 7.5.0 consist mostly of bug-fixes, and documentation updates, with one
1079 minor new feature. The `Audio` display element can now be assigned an element
1080 minor new feature. The `Audio` display element can now be assigned an element
1080 id when displayed in browser. See :ghpull:`11670`
1081 id when displayed in browser. See :ghpull:`11670`
1081
1082
1082 The major outstanding bug fix correct a change of behavior that was introduce
1083 The major outstanding bug fix correct a change of behavior that was introduce
1083 in 7.4.0 where some cell magics would not be able to access or modify global
1084 in 7.4.0 where some cell magics would not be able to access or modify global
1084 scope when using the ``@needs_local_scope`` decorator. This was typically
1085 scope when using the ``@needs_local_scope`` decorator. This was typically
1085 encountered with the ``%%time`` and ``%%timeit`` magics. See :ghissue:`11659`
1086 encountered with the ``%%time`` and ``%%timeit`` magics. See :ghissue:`11659`
1086 and :ghpull:`11698`.
1087 and :ghpull:`11698`.
1087
1088
1088 .. _whatsnew740:
1089 .. _whatsnew740:
1089
1090
1090 IPython 7.4.0
1091 IPython 7.4.0
1091 =============
1092 =============
1092
1093
1093 Unicode name completions
1094 Unicode name completions
1094 ------------------------
1095 ------------------------
1095
1096
1096 Previously, we provided completion for a unicode name with its relative symbol.
1097 Previously, we provided completion for a unicode name with its relative symbol.
1097 With this, now IPython provides complete suggestions to unicode name symbols.
1098 With this, now IPython provides complete suggestions to unicode name symbols.
1098
1099
1099 As on the PR, if user types ``\LAT<tab>``, IPython provides a list of
1100 As on the PR, if user types ``\LAT<tab>``, IPython provides a list of
1100 possible completions. In this case, it would be something like::
1101 possible completions. In this case, it would be something like::
1101
1102
1102 'LATIN CAPITAL LETTER A',
1103 'LATIN CAPITAL LETTER A',
1103 'LATIN CAPITAL LETTER B',
1104 'LATIN CAPITAL LETTER B',
1104 'LATIN CAPITAL LETTER C',
1105 'LATIN CAPITAL LETTER C',
1105 'LATIN CAPITAL LETTER D',
1106 'LATIN CAPITAL LETTER D',
1106 ....
1107 ....
1107
1108
1108 This help to type unicode character that do not have short latex aliases, and
1109 This help to type unicode character that do not have short latex aliases, and
1109 have long unicode names. for example ``Ν°``, ``\GREEK CAPITAL LETTER HETA``.
1110 have long unicode names. for example ``Ν°``, ``\GREEK CAPITAL LETTER HETA``.
1110
1111
1111 This feature was contributed by Luciana Marques :ghpull:`11583`.
1112 This feature was contributed by Luciana Marques :ghpull:`11583`.
1112
1113
1113 Make audio normalization optional
1114 Make audio normalization optional
1114 ---------------------------------
1115 ---------------------------------
1115
1116
1116 Added 'normalize' argument to `IPython.display.Audio`. This argument applies
1117 Added 'normalize' argument to `IPython.display.Audio`. This argument applies
1117 when audio data is given as an array of samples. The default of `normalize=True`
1118 when audio data is given as an array of samples. The default of `normalize=True`
1118 preserves prior behavior of normalizing the audio to the maximum possible range.
1119 preserves prior behavior of normalizing the audio to the maximum possible range.
1119 Setting to `False` disables normalization.
1120 Setting to `False` disables normalization.
1120
1121
1121
1122
1122 Miscellaneous
1123 Miscellaneous
1123 -------------
1124 -------------
1124
1125
1125 - Fix improper acceptation of ``return`` outside of functions. :ghpull:`11641`.
1126 - Fix improper acceptation of ``return`` outside of functions. :ghpull:`11641`.
1126 - Fixed PyQt 5.11 backwards incompatibility causing sip import failure.
1127 - Fixed PyQt 5.11 backwards incompatibility causing sip import failure.
1127 :ghpull:`11613`.
1128 :ghpull:`11613`.
1128 - Fix Bug where ``type?`` would crash IPython. :ghpull:`1608`.
1129 - Fix Bug where ``type?`` would crash IPython. :ghpull:`1608`.
1129 - Allow to apply ``@needs_local_scope`` to cell magics for convenience.
1130 - Allow to apply ``@needs_local_scope`` to cell magics for convenience.
1130 :ghpull:`11542`.
1131 :ghpull:`11542`.
1131
1132
1132 .. _whatsnew730:
1133 .. _whatsnew730:
1133
1134
1134 IPython 7.3.0
1135 IPython 7.3.0
1135 =============
1136 =============
1136
1137
1137 .. _whatsnew720:
1138 .. _whatsnew720:
1138
1139
1139 IPython 7.3.0 bring several bug fixes and small improvements that you will
1140 IPython 7.3.0 bring several bug fixes and small improvements that you will
1140 described bellow.
1141 described bellow.
1141
1142
1142 The biggest change to this release is the implementation of the ``%conda`` and
1143 The biggest change to this release is the implementation of the ``%conda`` and
1143 ``%pip`` magics, that will attempt to install packages in the **current
1144 ``%pip`` magics, that will attempt to install packages in the **current
1144 environment**. You may still need to restart your interpreter or kernel for the
1145 environment**. You may still need to restart your interpreter or kernel for the
1145 change to be taken into account, but it should simplify installation of packages
1146 change to be taken into account, but it should simplify installation of packages
1146 into remote environment. Installing using pip/conda from the command line is
1147 into remote environment. Installing using pip/conda from the command line is
1147 still the prefer method.
1148 still the prefer method.
1148
1149
1149 The ``%pip`` magic was already present, but was only printing a warning; now it
1150 The ``%pip`` magic was already present, but was only printing a warning; now it
1150 will actually forward commands to pip.
1151 will actually forward commands to pip.
1151
1152
1152 Misc bug fixes and improvements:
1153 Misc bug fixes and improvements:
1153
1154
1154 - Compatibility with Python 3.8.
1155 - Compatibility with Python 3.8.
1155 - Do not expand shell variable in execution magics, and added the
1156 - Do not expand shell variable in execution magics, and added the
1156 ``no_var_expand`` decorator for magic requiring a similar functionality
1157 ``no_var_expand`` decorator for magic requiring a similar functionality
1157 :ghpull:`11516`
1158 :ghpull:`11516`
1158 - Add ``%pip`` and ``%conda`` magic :ghpull:`11524`
1159 - Add ``%pip`` and ``%conda`` magic :ghpull:`11524`
1159 - Re-initialize posix aliases after a ``%reset`` :ghpull:`11528`
1160 - Re-initialize posix aliases after a ``%reset`` :ghpull:`11528`
1160 - Allow the IPython command line to run ``*.ipynb`` files :ghpull:`11529`
1161 - Allow the IPython command line to run ``*.ipynb`` files :ghpull:`11529`
1161
1162
1162 IPython 7.2.0
1163 IPython 7.2.0
1163 =============
1164 =============
1164
1165
1165 IPython 7.2.0 brings minor bugfixes, improvements, and new configuration options:
1166 IPython 7.2.0 brings minor bugfixes, improvements, and new configuration options:
1166
1167
1167 - Fix a bug preventing PySide2 GUI integration from working :ghpull:`11464`
1168 - Fix a bug preventing PySide2 GUI integration from working :ghpull:`11464`
1168 - Run CI on Mac OS ! :ghpull:`11471`
1169 - Run CI on Mac OS ! :ghpull:`11471`
1169 - Fix IPython "Demo" mode. :ghpull:`11498`
1170 - Fix IPython "Demo" mode. :ghpull:`11498`
1170 - Fix ``%run`` magic with path in name :ghpull:`11499`
1171 - Fix ``%run`` magic with path in name :ghpull:`11499`
1171 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
1172 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
1172 - Better rendering of signatures, especially long ones. :ghpull:`11505`
1173 - Better rendering of signatures, especially long ones. :ghpull:`11505`
1173 - Re-enable jedi by default if it's installed :ghpull:`11506`
1174 - Re-enable jedi by default if it's installed :ghpull:`11506`
1174 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
1175 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
1175
1176
1176
1177
1177 Added ability to show subclasses when using pinfo and other utilities
1178 Added ability to show subclasses when using pinfo and other utilities
1178 ---------------------------------------------------------------------
1179 ---------------------------------------------------------------------
1179
1180
1180 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
1181 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
1181
1182
1182 Special Thanks to Chris Mentzel of the Moore Foundation for this feature. Chris
1183 Special Thanks to Chris Mentzel of the Moore Foundation for this feature. Chris
1183 is one of the people who played a critical role in IPython/Jupyter getting
1184 is one of the people who played a critical role in IPython/Jupyter getting
1184 funding.
1185 funding.
1185
1186
1186 We are grateful for all the help Chris has given us over the years,
1187 We are grateful for all the help Chris has given us over the years,
1187 and we're now proud to have code contributed by Chris in IPython.
1188 and we're now proud to have code contributed by Chris in IPython.
1188
1189
1189 OSMagics.cd_force_quiet configuration option
1190 OSMagics.cd_force_quiet configuration option
1190 --------------------------------------------
1191 --------------------------------------------
1191
1192
1192 You can set this option to force the %cd magic to behave as if ``-q`` was passed:
1193 You can set this option to force the %cd magic to behave as if ``-q`` was passed:
1193 ::
1194 ::
1194
1195
1195 In [1]: cd /
1196 In [1]: cd /
1196 /
1197 /
1197
1198
1198 In [2]: %config OSMagics.cd_force_quiet = True
1199 In [2]: %config OSMagics.cd_force_quiet = True
1199
1200
1200 In [3]: cd /tmp
1201 In [3]: cd /tmp
1201
1202
1202 In [4]:
1203 In [4]:
1203
1204
1204 See :ghpull:`11491`
1205 See :ghpull:`11491`
1205
1206
1206 In vi editing mode, whether the prompt includes the current vi mode can now be configured
1207 In vi editing mode, whether the prompt includes the current vi mode can now be configured
1207 -----------------------------------------------------------------------------------------
1208 -----------------------------------------------------------------------------------------
1208
1209
1209 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
1210 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
1210 (default: True) to control this feature. See :ghpull:`11492`
1211 (default: True) to control this feature. See :ghpull:`11492`
1211
1212
1212 .. _whatsnew710:
1213 .. _whatsnew710:
1213
1214
1214 IPython 7.1.0
1215 IPython 7.1.0
1215 =============
1216 =============
1216
1217
1217 IPython 7.1.0 is the first minor release after 7.0.0 and mostly brings fixes to
1218 IPython 7.1.0 is the first minor release after 7.0.0 and mostly brings fixes to
1218 new features, internal refactoring, and fixes for regressions that happened during the 6.x->7.x
1219 new features, internal refactoring, and fixes for regressions that happened during the 6.x->7.x
1219 transition. It also brings **Compatibility with Python 3.7.1**, as we're
1220 transition. It also brings **Compatibility with Python 3.7.1**, as we're
1220 unwillingly relying on a bug in CPython.
1221 unwillingly relying on a bug in CPython.
1221
1222
1222 New Core Dev:
1223 New Core Dev:
1223
1224
1224 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
1225 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
1225 work on prompt_toolkit, and we'd like to recognise his impact by giving him
1226 work on prompt_toolkit, and we'd like to recognise his impact by giving him
1226 commit rights. :ghissue:`11397`
1227 commit rights. :ghissue:`11397`
1227
1228
1228 Notable Changes
1229 Notable Changes
1229
1230
1230 - Major update of "latex to unicode" tab completion map (see below)
1231 - Major update of "latex to unicode" tab completion map (see below)
1231
1232
1232 Notable New Features:
1233 Notable New Features:
1233
1234
1234 - Restore functionality and documentation of the **sphinx directive**, which
1235 - Restore functionality and documentation of the **sphinx directive**, which
1235 is now stricter (fail on error by daefault), has new configuration options,
1236 is now stricter (fail on error by daefault), has new configuration options,
1236 has a brand new documentation page :ref:`ipython_directive` (which needs
1237 has a brand new documentation page :ref:`ipython_directive` (which needs
1237 some cleanup). It is also now *tested* so we hope to have less regressions.
1238 some cleanup). It is also now *tested* so we hope to have less regressions.
1238 :ghpull:`11402`
1239 :ghpull:`11402`
1239
1240
1240 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
1241 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
1241 allowing a custom width and height to be set instead of using the video's
1242 allowing a custom width and height to be set instead of using the video's
1242 width and height. :ghpull:`11353`
1243 width and height. :ghpull:`11353`
1243
1244
1244 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
1245 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
1245
1246
1246 - Allow Dynamic switching of editing mode between vi/emacs and show
1247 - Allow Dynamic switching of editing mode between vi/emacs and show
1247 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
1248 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
1248 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
1249 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
1249 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically switch
1250 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically switch
1250 between modes.
1251 between modes.
1251
1252
1252
1253
1253 Notable Fixes:
1254 Notable Fixes:
1254
1255
1255 - Fix entering of **multi-line blocks in terminal** IPython, and various
1256 - Fix entering of **multi-line blocks in terminal** IPython, and various
1256 crashes in the new input transformation machinery :ghpull:`11354`,
1257 crashes in the new input transformation machinery :ghpull:`11354`,
1257 :ghpull:`11356`, :ghpull:`11358`. These also fix a **Compatibility bug
1258 :ghpull:`11356`, :ghpull:`11358`. These also fix a **Compatibility bug
1258 with Python 3.7.1**.
1259 with Python 3.7.1**.
1259
1260
1260 - Fix moving through generator stack in ipdb :ghpull:`11266`
1261 - Fix moving through generator stack in ipdb :ghpull:`11266`
1261
1262
1262 - %Magic command arguments now support quoting. :ghpull:`11330`
1263 - %Magic command arguments now support quoting. :ghpull:`11330`
1263
1264
1264 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
1265 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
1265
1266
1266 - Remove implicit dependency on ``ipython_genutils`` :ghpull:`11317`
1267 - Remove implicit dependency on ``ipython_genutils`` :ghpull:`11317`
1267
1268
1268 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
1269 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
1269 mode. :ghpull:`11382`
1270 mode. :ghpull:`11382`
1270
1271
1271 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
1272 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
1272 nested code blocks :ghpull:`11418`
1273 nested code blocks :ghpull:`11418`
1273
1274
1274 - Fix instructions for custom shortcuts :ghpull:`11426`
1275 - Fix instructions for custom shortcuts :ghpull:`11426`
1275
1276
1276
1277
1277 Notable Internals improvements:
1278 Notable Internals improvements:
1278
1279
1279 - Use of ``os.scandir`` (Python 3 only) to speed up some file system operations.
1280 - Use of ``os.scandir`` (Python 3 only) to speed up some file system operations.
1280 :ghpull:`11365`
1281 :ghpull:`11365`
1281
1282
1282 - use ``perf_counter`` instead of ``clock`` for more precise
1283 - use ``perf_counter`` instead of ``clock`` for more precise
1283 timing results with ``%time`` :ghpull:`11376`
1284 timing results with ``%time`` :ghpull:`11376`
1284
1285
1285 Many thanks to all the contributors and in particular to ``bartskowron`` and
1286 Many thanks to all the contributors and in particular to ``bartskowron`` and
1286 ``tonyfast`` who handled some pretty complicated bugs in the input machinery. We
1287 ``tonyfast`` who handled some pretty complicated bugs in the input machinery. We
1287 had a number of first time contributors and maybe hacktoberfest participants that
1288 had a number of first time contributors and maybe hacktoberfest participants that
1288 made significant contributions and helped us free some time to focus on more
1289 made significant contributions and helped us free some time to focus on more
1289 complicated bugs.
1290 complicated bugs.
1290
1291
1291 You
1292 You
1292 can see all the closed issues and Merged PR, new features and fixes `here
1293 can see all the closed issues and Merged PR, new features and fixes `here
1293 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
1294 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
1294
1295
1295 Unicode Completion update
1296 Unicode Completion update
1296 -------------------------
1297 -------------------------
1297
1298
1298 In IPython 7.1 the Unicode completion map has been updated and synchronized with
1299 In IPython 7.1 the Unicode completion map has been updated and synchronized with
1299 the Julia language.
1300 the Julia language.
1300
1301
1301 Added and removed character characters:
1302 Added and removed character characters:
1302
1303
1303 ``\jmath`` (``Θ·``), ``\\underleftrightarrow`` (U+034D, combining) have been
1304 ``\jmath`` (``Θ·``), ``\\underleftrightarrow`` (U+034D, combining) have been
1304 added, while ``\\textasciicaron`` have been removed
1305 added, while ``\\textasciicaron`` have been removed
1305
1306
1306 Some sequences have seen their prefix removed:
1307 Some sequences have seen their prefix removed:
1307
1308
1308 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
1309 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
1309 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
1310 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
1310 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
1311 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
1311 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
1312 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
1312
1313
1313 Some sequences have seen their prefix shortened:
1314 Some sequences have seen their prefix shortened:
1314
1315
1315 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
1316 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
1316 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
1317 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
1317 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
1318 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
1318 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
1319 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
1319
1320
1320 A couple of characters had their sequence simplified:
1321 A couple of characters had their sequence simplified:
1321
1322
1322 - ``Γ°``, type ``\dh<tab>``, instead of ``\eth<tab>``
1323 - ``Γ°``, type ``\dh<tab>``, instead of ``\eth<tab>``
1323 - ``Δ§``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
1324 - ``Δ§``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
1324 - ``ΙΈ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
1325 - ``ΙΈ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
1325 - ``Ο΄``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
1326 - ``Ο΄``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
1326 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
1327 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
1327 - ``β„Ž``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
1328 - ``β„Ž``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
1328
1329
1329 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
1330 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
1330
1331
1331 A couple of sequences have been updated:
1332 A couple of sequences have been updated:
1332
1333
1333 - ``\varepsilon`` now gives ``Ι›`` (GREEK SMALL LETTER EPSILON) instead of ``Ξ΅`` (GREEK LUNATE EPSILON SYMBOL),
1334 - ``\varepsilon`` now gives ``Ι›`` (GREEK SMALL LETTER EPSILON) instead of ``Ξ΅`` (GREEK LUNATE EPSILON SYMBOL),
1334 - ``\underbar`` now gives U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
1335 - ``\underbar`` now gives U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
1335
1336
1336
1337
1337 .. _whatsnew700:
1338 .. _whatsnew700:
1338
1339
1339 IPython 7.0.0
1340 IPython 7.0.0
1340 =============
1341 =============
1341
1342
1342 Released Thursday September 27th, 2018
1343 Released Thursday September 27th, 2018
1343
1344
1344 IPython 7 includes major feature improvements.
1345 IPython 7 includes major feature improvements.
1345 This is also the second major version of IPython to support only
1346 This is also the second major version of IPython to support only
1346 Python 3 – starting at Python 3.4. Python 2 is still community-supported
1347 Python 3 – starting at Python 3.4. Python 2 is still community-supported
1347 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
1348 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
1348 is on Jan 1st 2020.
1349 is on Jan 1st 2020.
1349
1350
1350 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
1351 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
1351 backported more than `70 Pull-Requests
1352 backported more than `70 Pull-Requests
1352 <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>`_
1353 <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>`_
1353
1354
1354 The IPython 6.x branch will likely not see any further release unless critical
1355 The IPython 6.x branch will likely not see any further release unless critical
1355 bugs are found.
1356 bugs are found.
1356
1357
1357 Make sure you have pip > 9.0 before upgrading. You should be able to update by running:
1358 Make sure you have pip > 9.0 before upgrading. You should be able to update by running:
1358
1359
1359 .. code::
1360 .. code::
1360
1361
1361 pip install ipython --upgrade
1362 pip install ipython --upgrade
1362
1363
1363 .. only:: ipydev
1364 .. only:: ipydev
1364
1365
1365 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
1366 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
1366 version, use pip ``--pre`` flag.
1367 version, use pip ``--pre`` flag.
1367
1368
1368 .. code::
1369 .. code::
1369
1370
1370 pip install ipython --upgrade --pre
1371 pip install ipython --upgrade --pre
1371
1372
1372
1373
1373 Or, if you have conda installed:
1374 Or, if you have conda installed:
1374
1375
1375 .. code::
1376 .. code::
1376
1377
1377 conda install ipython
1378 conda install ipython
1378
1379
1379
1380
1380
1381
1381 Prompt Toolkit 2.0
1382 Prompt Toolkit 2.0
1382 ------------------
1383 ------------------
1383
1384
1384 IPython 7.0+ now uses ``prompt_toolkit 2.0``. If you still need to use an earlier
1385 IPython 7.0+ now uses ``prompt_toolkit 2.0``. If you still need to use an earlier
1385 ``prompt_toolkit`` version, you may need to pin IPython to ``<7.0``.
1386 ``prompt_toolkit`` version, you may need to pin IPython to ``<7.0``.
1386
1387
1387 Autowait: Asynchronous REPL
1388 Autowait: Asynchronous REPL
1388 ---------------------------
1389 ---------------------------
1389
1390
1390 Staring with IPython 7.0 on Python 3.6+, IPython can automatically ``await``
1391 Staring with IPython 7.0 on Python 3.6+, IPython can automatically ``await``
1391 top level code. You should not need to access an event loop or runner
1392 top level code. You should not need to access an event loop or runner
1392 yourself. To learn more, read the :ref:`autoawait` section of our docs, see
1393 yourself. To learn more, read the :ref:`autoawait` section of our docs, see
1393 :ghpull:`11265`, or try the following code::
1394 :ghpull:`11265`, or try the following code::
1394
1395
1395 Python 3.6.0
1396 Python 3.6.0
1396 Type 'copyright', 'credits' or 'license' for more information
1397 Type 'copyright', 'credits' or 'license' for more information
1397 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
1398 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
1398
1399
1399 In [1]: import aiohttp
1400 In [1]: import aiohttp
1400 ...: result = aiohttp.get('https://api.github.com')
1401 ...: result = aiohttp.get('https://api.github.com')
1401
1402
1402 In [2]: response = await result
1403 In [2]: response = await result
1403 <pause for a few 100s ms>
1404 <pause for a few 100s ms>
1404
1405
1405 In [3]: await response.json()
1406 In [3]: await response.json()
1406 Out[3]:
1407 Out[3]:
1407 {'authorizations_url': 'https://api.github.com/authorizations',
1408 {'authorizations_url': 'https://api.github.com/authorizations',
1408 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
1409 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
1409 ...
1410 ...
1410 }
1411 }
1411
1412
1412 .. note::
1413 .. note::
1413
1414
1414 Async integration is experimental code, behavior may change or be removed
1415 Async integration is experimental code, behavior may change or be removed
1415 between Python and IPython versions without warnings.
1416 between Python and IPython versions without warnings.
1416
1417
1417 Integration is by default with `asyncio`, but other libraries can be configured --
1418 Integration is by default with `asyncio`, but other libraries can be configured --
1418 like ``curio`` or ``trio`` -- to improve concurrency in the REPL::
1419 like ``curio`` or ``trio`` -- to improve concurrency in the REPL::
1419
1420
1420 In [1]: %autoawait trio
1421 In [1]: %autoawait trio
1421
1422
1422 In [2]: import trio
1423 In [2]: import trio
1423
1424
1424 In [3]: async def child(i):
1425 In [3]: async def child(i):
1425 ...: print(" child %s goes to sleep"%i)
1426 ...: print(" child %s goes to sleep"%i)
1426 ...: await trio.sleep(2)
1427 ...: await trio.sleep(2)
1427 ...: print(" child %s wakes up"%i)
1428 ...: print(" child %s wakes up"%i)
1428
1429
1429 In [4]: print('parent start')
1430 In [4]: print('parent start')
1430 ...: async with trio.open_nursery() as n:
1431 ...: async with trio.open_nursery() as n:
1431 ...: for i in range(3):
1432 ...: for i in range(3):
1432 ...: n.spawn(child, i)
1433 ...: n.spawn(child, i)
1433 ...: print('parent end')
1434 ...: print('parent end')
1434 parent start
1435 parent start
1435 child 2 goes to sleep
1436 child 2 goes to sleep
1436 child 0 goes to sleep
1437 child 0 goes to sleep
1437 child 1 goes to sleep
1438 child 1 goes to sleep
1438 <about 2 seconds pause>
1439 <about 2 seconds pause>
1439 child 2 wakes up
1440 child 2 wakes up
1440 child 1 wakes up
1441 child 1 wakes up
1441 child 0 wakes up
1442 child 0 wakes up
1442 parent end
1443 parent end
1443
1444
1444 See :ref:`autoawait` for more information.
1445 See :ref:`autoawait` for more information.
1445
1446
1446
1447
1447 Asynchronous code in a Notebook interface or any other frontend using the
1448 Asynchronous code in a Notebook interface or any other frontend using the
1448 Jupyter Protocol will require further updates to the IPykernel package.
1449 Jupyter Protocol will require further updates to the IPykernel package.
1449
1450
1450 Non-Asynchronous code
1451 Non-Asynchronous code
1451 ~~~~~~~~~~~~~~~~~~~~~
1452 ~~~~~~~~~~~~~~~~~~~~~
1452
1453
1453 As the internal API of IPython is now asynchronous, IPython needs to run under
1454 As the internal API of IPython is now asynchronous, IPython needs to run under
1454 an event loop. In order to allow many workflows, (like using the :magic:`%run`
1455 an event loop. In order to allow many workflows, (like using the :magic:`%run`
1455 magic, or copy-pasting code that explicitly starts/stop event loop), when
1456 magic, or copy-pasting code that explicitly starts/stop event loop), when
1456 top-level code is detected as not being asynchronous, IPython code is advanced
1457 top-level code is detected as not being asynchronous, IPython code is advanced
1457 via a pseudo-synchronous runner, and may not advance pending tasks.
1458 via a pseudo-synchronous runner, and may not advance pending tasks.
1458
1459
1459 Change to Nested Embed
1460 Change to Nested Embed
1460 ~~~~~~~~~~~~~~~~~~~~~~
1461 ~~~~~~~~~~~~~~~~~~~~~~
1461
1462
1462 The introduction of the ability to run async code had some effect on the
1463 The introduction of the ability to run async code had some effect on the
1463 ``IPython.embed()`` API. By default, embed will not allow you to run asynchronous
1464 ``IPython.embed()`` API. By default, embed will not allow you to run asynchronous
1464 code unless an event loop is specified.
1465 code unless an event loop is specified.
1465
1466
1466 Effects on Magics
1467 Effects on Magics
1467 ~~~~~~~~~~~~~~~~~
1468 ~~~~~~~~~~~~~~~~~
1468
1469
1469 Some magics will not work with async until they're updated.
1470 Some magics will not work with async until they're updated.
1470 Contributions welcome.
1471 Contributions welcome.
1471
1472
1472 Expected Future changes
1473 Expected Future changes
1473 ~~~~~~~~~~~~~~~~~~~~~~~
1474 ~~~~~~~~~~~~~~~~~~~~~~~
1474
1475
1475 We expect more internal but public IPython functions to become ``async``, and
1476 We expect more internal but public IPython functions to become ``async``, and
1476 will likely end up having a persistent event loop while IPython is running.
1477 will likely end up having a persistent event loop while IPython is running.
1477
1478
1478 Thanks
1479 Thanks
1479 ~~~~~~
1480 ~~~~~~
1480
1481
1481 This release took more than a year in the making.
1482 This release took more than a year in the making.
1482 The code was rebased a number of
1483 The code was rebased a number of
1483 times; leading to commit authorship that may have been lost in the final
1484 times; leading to commit authorship that may have been lost in the final
1484 Pull-Request. Huge thanks to many people for contribution, discussion, code,
1485 Pull-Request. Huge thanks to many people for contribution, discussion, code,
1485 documentation, use-cases: dalejung, danielballan, ellisonbg, fperez, gnestor,
1486 documentation, use-cases: dalejung, danielballan, ellisonbg, fperez, gnestor,
1486 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
1487 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
1487
1488
1488
1489
1489 Autoreload Improvement
1490 Autoreload Improvement
1490 ----------------------
1491 ----------------------
1491
1492
1492 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
1493 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
1493 classes. Earlier, only methods existing as of the initial import were being
1494 classes. Earlier, only methods existing as of the initial import were being
1494 tracked and updated.
1495 tracked and updated.
1495
1496
1496 This new feature helps dual environment development - Jupyter+IDE - where the
1497 This new feature helps dual environment development - Jupyter+IDE - where the
1497 code gradually moves from notebook cells to package files as it gets
1498 code gradually moves from notebook cells to package files as it gets
1498 structured.
1499 structured.
1499
1500
1500 **Example**: An instance of the class ``MyClass`` will be able to access the
1501 **Example**: An instance of the class ``MyClass`` will be able to access the
1501 method ``cube()`` after it is uncommented and the file ``file1.py`` is saved on
1502 method ``cube()`` after it is uncommented and the file ``file1.py`` is saved on
1502 disk.
1503 disk.
1503
1504
1504
1505
1505 .. code::
1506 .. code::
1506
1507
1507 # notebook
1508 # notebook
1508
1509
1509 from mymodule import MyClass
1510 from mymodule import MyClass
1510 first = MyClass(5)
1511 first = MyClass(5)
1511
1512
1512 .. code::
1513 .. code::
1513
1514
1514 # mymodule/file1.py
1515 # mymodule/file1.py
1515
1516
1516 class MyClass:
1517 class MyClass:
1517
1518
1518 def __init__(self, a=10):
1519 def __init__(self, a=10):
1519 self.a = a
1520 self.a = a
1520
1521
1521 def square(self):
1522 def square(self):
1522 print('compute square')
1523 print('compute square')
1523 return self.a*self.a
1524 return self.a*self.a
1524
1525
1525 # def cube(self):
1526 # def cube(self):
1526 # print('compute cube')
1527 # print('compute cube')
1527 # return self.a*self.a*self.a
1528 # return self.a*self.a*self.a
1528
1529
1529
1530
1530
1531
1531
1532
1532 Misc
1533 Misc
1533 ----
1534 ----
1534
1535
1535 The autoindent feature that was deprecated in 5.x was re-enabled and
1536 The autoindent feature that was deprecated in 5.x was re-enabled and
1536 un-deprecated in :ghpull:`11257`
1537 un-deprecated in :ghpull:`11257`
1537
1538
1538 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
1539 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
1539 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
1540 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
1540
1541
1541
1542
1542 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
1543 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
1543 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
1544 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
1544 the given code is non-zero (thus halting execution of further cells in a
1545 the given code is non-zero (thus halting execution of further cells in a
1545 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
1546 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
1546
1547
1547
1548
1548 Deprecations
1549 Deprecations
1549 ------------
1550 ------------
1550
1551
1551 A couple of unused functions and methods have been deprecated and will be removed
1552 A couple of unused functions and methods have been deprecated and will be removed
1552 in future versions:
1553 in future versions:
1553
1554
1554 - ``IPython.utils.io.raw_print_err``
1555 - ``IPython.utils.io.raw_print_err``
1555 - ``IPython.utils.io.raw_print``
1556 - ``IPython.utils.io.raw_print``
1556
1557
1557
1558
1558 Backwards incompatible changes
1559 Backwards incompatible changes
1559 ------------------------------
1560 ------------------------------
1560
1561
1561 * The API for transforming input before it is parsed as Python code has been
1562 * The API for transforming input before it is parsed as Python code has been
1562 completely redesigned: any custom input transformations will need to be
1563 completely redesigned: any custom input transformations will need to be
1563 rewritten. See :doc:`/config/inputtransforms` for details of the new API.
1564 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