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