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