##// END OF EJS Templates
Merge branch '7.x' into auto-backport-of-pr-13600-on-7.x
Matthias Bussonnier -
r27629:504079a8 merge
parent child Browse files
Show More
@@ -1,750 +1,752 b''
1 1 """Input transformer machinery to support IPython special syntax.
2 2
3 3 This includes the machinery to recognise and transform ``%magic`` commands,
4 4 ``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
5 5
6 6 Added: IPython 7.0. Replaces inputsplitter and inputtransformer which were
7 7 deprecated in 7.0.
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 import ast
14 14 import sys
15 15 from codeop import CommandCompiler, Compile
16 16 import re
17 17 import tokenize
18 18 from typing import List, Tuple, Union
19 19 import warnings
20 20
21 21 _indent_re = re.compile(r'^[ \t]+')
22 22
23 23 def leading_empty_lines(lines):
24 24 """Remove leading empty lines
25 25
26 26 If the leading lines are empty or contain only whitespace, they will be
27 27 removed.
28 28 """
29 29 if not lines:
30 30 return lines
31 31 for i, line in enumerate(lines):
32 32 if line and not line.isspace():
33 33 return lines[i:]
34 34 return lines
35 35
36 36 def leading_indent(lines):
37 37 """Remove leading indentation.
38 38
39 39 If the first line starts with a spaces or tabs, the same whitespace will be
40 40 removed from each following line in the cell.
41 41 """
42 42 if not lines:
43 43 return lines
44 44 m = _indent_re.match(lines[0])
45 45 if not m:
46 46 return lines
47 47 space = m.group(0)
48 48 n = len(space)
49 49 return [l[n:] if l.startswith(space) else l
50 50 for l in lines]
51 51
52 52 class PromptStripper:
53 53 """Remove matching input prompts from a block of input.
54 54
55 55 Parameters
56 56 ----------
57 57 prompt_re : regular expression
58 58 A regular expression matching any input prompt (including continuation,
59 59 e.g. ``...``)
60 60 initial_re : regular expression, optional
61 61 A regular expression matching only the initial prompt, but not continuation.
62 62 If no initial expression is given, prompt_re will be used everywhere.
63 63 Used mainly for plain Python prompts (``>>>``), where the continuation prompt
64 64 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
65 65
66 66 Notes
67 67 -----
68 68
69 69 If initial_re and prompt_re differ,
70 70 only initial_re will be tested against the first line.
71 71 If any prompt is found on the first two lines,
72 72 prompts will be stripped from the rest of the block.
73 73 """
74 74 def __init__(self, prompt_re, initial_re=None):
75 75 self.prompt_re = prompt_re
76 76 self.initial_re = initial_re or prompt_re
77 77
78 78 def _strip(self, lines):
79 79 return [self.prompt_re.sub('', l, count=1) for l in lines]
80 80
81 81 def __call__(self, lines):
82 82 if not lines:
83 83 return lines
84 84 if self.initial_re.match(lines[0]) or \
85 85 (len(lines) > 1 and self.prompt_re.match(lines[1])):
86 86 return self._strip(lines)
87 87 return lines
88 88
89 89 classic_prompt = PromptStripper(
90 90 prompt_re=re.compile(r'^(>>>|\.\.\.)( |$)'),
91 91 initial_re=re.compile(r'^>>>( |$)')
92 92 )
93 93
94 94 ipython_prompt = PromptStripper(re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)'))
95 95
96 96 def cell_magic(lines):
97 97 if not lines or not lines[0].startswith('%%'):
98 98 return lines
99 99 if re.match(r'%%\w+\?', lines[0]):
100 100 # This case will be handled by help_end
101 101 return lines
102 102 magic_name, _, first_line = lines[0][2:].rstrip().partition(' ')
103 103 body = ''.join(lines[1:])
104 104 return ['get_ipython().run_cell_magic(%r, %r, %r)\n'
105 105 % (magic_name, first_line, body)]
106 106
107 107
108 108 def _find_assign_op(token_line) -> Union[int, None]:
109 109 """Get the index of the first assignment in the line ('=' not inside brackets)
110 110
111 111 Note: We don't try to support multiple special assignment (a = b = %foo)
112 112 """
113 113 paren_level = 0
114 114 for i, ti in enumerate(token_line):
115 115 s = ti.string
116 116 if s == '=' and paren_level == 0:
117 117 return i
118 118 if s in {'(','[','{'}:
119 119 paren_level += 1
120 120 elif s in {')', ']', '}'}:
121 121 if paren_level > 0:
122 122 paren_level -= 1
123 123
124 124 def find_end_of_continued_line(lines, start_line: int):
125 125 """Find the last line of a line explicitly extended using backslashes.
126 126
127 127 Uses 0-indexed line numbers.
128 128 """
129 129 end_line = start_line
130 130 while lines[end_line].endswith('\\\n'):
131 131 end_line += 1
132 132 if end_line >= len(lines):
133 133 break
134 134 return end_line
135 135
136 136 def assemble_continued_line(lines, start: Tuple[int, int], end_line: int):
137 137 r"""Assemble a single line from multiple continued line pieces
138 138
139 139 Continued lines are lines ending in ``\``, and the line following the last
140 140 ``\`` in the block.
141 141
142 142 For example, this code continues over multiple lines::
143 143
144 144 if (assign_ix is not None) \
145 145 and (len(line) >= assign_ix + 2) \
146 146 and (line[assign_ix+1].string == '%') \
147 147 and (line[assign_ix+2].type == tokenize.NAME):
148 148
149 149 This statement contains four continued line pieces.
150 150 Assembling these pieces into a single line would give::
151 151
152 152 if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[...
153 153
154 154 This uses 0-indexed line numbers. *start* is (lineno, colno).
155 155
156 156 Used to allow ``%magic`` and ``!system`` commands to be continued over
157 157 multiple lines.
158 158 """
159 159 parts = [lines[start[0]][start[1]:]] + lines[start[0]+1:end_line+1]
160 160 return ' '.join([p.rstrip()[:-1] for p in parts[:-1]] # Strip backslash+newline
161 161 + [parts[-1].rstrip()]) # Strip newline from last line
162 162
163 163 class TokenTransformBase:
164 164 """Base class for transformations which examine tokens.
165 165
166 166 Special syntax should not be transformed when it occurs inside strings or
167 167 comments. This is hard to reliably avoid with regexes. The solution is to
168 168 tokenise the code as Python, and recognise the special syntax in the tokens.
169 169
170 170 IPython's special syntax is not valid Python syntax, so tokenising may go
171 171 wrong after the special syntax starts. These classes therefore find and
172 172 transform *one* instance of special syntax at a time into regular Python
173 173 syntax. After each transformation, tokens are regenerated to find the next
174 174 piece of special syntax.
175 175
176 176 Subclasses need to implement one class method (find)
177 177 and one regular method (transform).
178 178
179 179 The priority attribute can select which transformation to apply if multiple
180 180 transformers match in the same place. Lower numbers have higher priority.
181 181 This allows "%magic?" to be turned into a help call rather than a magic call.
182 182 """
183 183 # Lower numbers -> higher priority (for matches in the same location)
184 184 priority = 10
185 185
186 186 def sortby(self):
187 187 return self.start_line, self.start_col, self.priority
188 188
189 189 def __init__(self, start):
190 190 self.start_line = start[0] - 1 # Shift from 1-index to 0-index
191 191 self.start_col = start[1]
192 192
193 193 @classmethod
194 194 def find(cls, tokens_by_line):
195 195 """Find one instance of special syntax in the provided tokens.
196 196
197 197 Tokens are grouped into logical lines for convenience,
198 198 so it is easy to e.g. look at the first token of each line.
199 199 *tokens_by_line* is a list of lists of tokenize.TokenInfo objects.
200 200
201 201 This should return an instance of its class, pointing to the start
202 202 position it has found, or None if it found no match.
203 203 """
204 204 raise NotImplementedError
205 205
206 206 def transform(self, lines: List[str]):
207 207 """Transform one instance of special syntax found by ``find()``
208 208
209 209 Takes a list of strings representing physical lines,
210 210 returns a similar list of transformed lines.
211 211 """
212 212 raise NotImplementedError
213 213
214 214 class MagicAssign(TokenTransformBase):
215 215 """Transformer for assignments from magics (a = %foo)"""
216 216 @classmethod
217 217 def find(cls, tokens_by_line):
218 218 """Find the first magic assignment (a = %foo) in the cell.
219 219 """
220 220 for line in tokens_by_line:
221 221 assign_ix = _find_assign_op(line)
222 222 if (assign_ix is not None) \
223 223 and (len(line) >= assign_ix + 2) \
224 224 and (line[assign_ix+1].string == '%') \
225 225 and (line[assign_ix+2].type == tokenize.NAME):
226 226 return cls(line[assign_ix+1].start)
227 227
228 228 def transform(self, lines: List[str]):
229 229 """Transform a magic assignment found by the ``find()`` classmethod.
230 230 """
231 231 start_line, start_col = self.start_line, self.start_col
232 232 lhs = lines[start_line][:start_col]
233 233 end_line = find_end_of_continued_line(lines, start_line)
234 234 rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
235 235 assert rhs.startswith('%'), rhs
236 236 magic_name, _, args = rhs[1:].partition(' ')
237 237
238 238 lines_before = lines[:start_line]
239 239 call = "get_ipython().run_line_magic({!r}, {!r})".format(magic_name, args)
240 240 new_line = lhs + call + '\n'
241 241 lines_after = lines[end_line+1:]
242 242
243 243 return lines_before + [new_line] + lines_after
244 244
245 245
246 246 class SystemAssign(TokenTransformBase):
247 247 """Transformer for assignments from system commands (a = !foo)"""
248 248 @classmethod
249 249 def find(cls, tokens_by_line):
250 250 """Find the first system assignment (a = !foo) in the cell.
251 251 """
252 252 for line in tokens_by_line:
253 253 assign_ix = _find_assign_op(line)
254 254 if (assign_ix is not None) \
255 255 and not line[assign_ix].line.strip().startswith('=') \
256 256 and (len(line) >= assign_ix + 2) \
257 257 and (line[assign_ix + 1].type == tokenize.ERRORTOKEN):
258 258 ix = assign_ix + 1
259 259
260 260 while ix < len(line) and line[ix].type == tokenize.ERRORTOKEN:
261 261 if line[ix].string == '!':
262 262 return cls(line[ix].start)
263 263 elif not line[ix].string.isspace():
264 264 break
265 265 ix += 1
266 266
267 267 def transform(self, lines: List[str]):
268 268 """Transform a system assignment found by the ``find()`` classmethod.
269 269 """
270 270 start_line, start_col = self.start_line, self.start_col
271 271
272 272 lhs = lines[start_line][:start_col]
273 273 end_line = find_end_of_continued_line(lines, start_line)
274 274 rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
275 275 assert rhs.startswith('!'), rhs
276 276 cmd = rhs[1:]
277 277
278 278 lines_before = lines[:start_line]
279 279 call = "get_ipython().getoutput({!r})".format(cmd)
280 280 new_line = lhs + call + '\n'
281 281 lines_after = lines[end_line + 1:]
282 282
283 283 return lines_before + [new_line] + lines_after
284 284
285 285 # The escape sequences that define the syntax transformations IPython will
286 286 # apply to user input. These can NOT be just changed here: many regular
287 287 # expressions and other parts of the code may use their hardcoded values, and
288 288 # for all intents and purposes they constitute the 'IPython syntax', so they
289 289 # should be considered fixed.
290 290
291 291 ESC_SHELL = '!' # Send line to underlying system shell
292 292 ESC_SH_CAP = '!!' # Send line to system shell and capture output
293 293 ESC_HELP = '?' # Find information about object
294 294 ESC_HELP2 = '??' # Find extra-detailed information about object
295 295 ESC_MAGIC = '%' # Call magic function
296 296 ESC_MAGIC2 = '%%' # Call cell-magic function
297 297 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
298 298 ESC_QUOTE2 = ';' # Quote all args as a single string, call
299 299 ESC_PAREN = '/' # Call first argument with rest of line as arguments
300 300
301 301 ESCAPE_SINGLES = {'!', '?', '%', ',', ';', '/'}
302 302 ESCAPE_DOUBLES = {'!!', '??'} # %% (cell magic) is handled separately
303 303
304 304 def _make_help_call(target, esc, next_input=None):
305 305 """Prepares a pinfo(2)/psearch call from a target name and the escape
306 306 (i.e. ? or ??)"""
307 307 method = 'pinfo2' if esc == '??' \
308 308 else 'psearch' if '*' in target \
309 309 else 'pinfo'
310 310 arg = " ".join([method, target])
311 311 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
312 312 t_magic_name, _, t_magic_arg_s = arg.partition(' ')
313 313 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
314 314 if next_input is None:
315 315 return 'get_ipython().run_line_magic(%r, %r)' % (t_magic_name, t_magic_arg_s)
316 316 else:
317 317 return 'get_ipython().set_next_input(%r);get_ipython().run_line_magic(%r, %r)' % \
318 318 (next_input, t_magic_name, t_magic_arg_s)
319 319
320 320 def _tr_help(content):
321 321 """Translate lines escaped with: ?
322 322
323 323 A naked help line should fire the intro help screen (shell.show_usage())
324 324 """
325 325 if not content:
326 326 return 'get_ipython().show_usage()'
327 327
328 328 return _make_help_call(content, '?')
329 329
330 330 def _tr_help2(content):
331 331 """Translate lines escaped with: ??
332 332
333 333 A naked help line should fire the intro help screen (shell.show_usage())
334 334 """
335 335 if not content:
336 336 return 'get_ipython().show_usage()'
337 337
338 338 return _make_help_call(content, '??')
339 339
340 340 def _tr_magic(content):
341 341 "Translate lines escaped with a percent sign: %"
342 342 name, _, args = content.partition(' ')
343 343 return 'get_ipython().run_line_magic(%r, %r)' % (name, args)
344 344
345 345 def _tr_quote(content):
346 346 "Translate lines escaped with a comma: ,"
347 347 name, _, args = content.partition(' ')
348 348 return '%s("%s")' % (name, '", "'.join(args.split()) )
349 349
350 350 def _tr_quote2(content):
351 351 "Translate lines escaped with a semicolon: ;"
352 352 name, _, args = content.partition(' ')
353 353 return '%s("%s")' % (name, args)
354 354
355 355 def _tr_paren(content):
356 356 "Translate lines escaped with a slash: /"
357 357 name, _, args = content.partition(' ')
358 358 return '%s(%s)' % (name, ", ".join(args.split()))
359 359
360 360 tr = { ESC_SHELL : 'get_ipython().system({!r})'.format,
361 361 ESC_SH_CAP : 'get_ipython().getoutput({!r})'.format,
362 362 ESC_HELP : _tr_help,
363 363 ESC_HELP2 : _tr_help2,
364 364 ESC_MAGIC : _tr_magic,
365 365 ESC_QUOTE : _tr_quote,
366 366 ESC_QUOTE2 : _tr_quote2,
367 367 ESC_PAREN : _tr_paren }
368 368
369 369 class EscapedCommand(TokenTransformBase):
370 370 """Transformer for escaped commands like %foo, !foo, or /foo"""
371 371 @classmethod
372 372 def find(cls, tokens_by_line):
373 373 """Find the first escaped command (%foo, !foo, etc.) in the cell.
374 374 """
375 375 for line in tokens_by_line:
376 376 if not line:
377 377 continue
378 378 ix = 0
379 379 ll = len(line)
380 380 while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
381 381 ix += 1
382 382 if ix >= ll:
383 383 continue
384 384 if line[ix].string in ESCAPE_SINGLES:
385 385 return cls(line[ix].start)
386 386
387 387 def transform(self, lines):
388 388 """Transform an escaped line found by the ``find()`` classmethod.
389 389 """
390 390 start_line, start_col = self.start_line, self.start_col
391 391
392 392 indent = lines[start_line][:start_col]
393 393 end_line = find_end_of_continued_line(lines, start_line)
394 394 line = assemble_continued_line(lines, (start_line, start_col), end_line)
395 395
396 396 if len(line) > 1 and line[:2] in ESCAPE_DOUBLES:
397 397 escape, content = line[:2], line[2:]
398 398 else:
399 399 escape, content = line[:1], line[1:]
400 400
401 401 if escape in tr:
402 402 call = tr[escape](content)
403 403 else:
404 404 call = ''
405 405
406 406 lines_before = lines[:start_line]
407 407 new_line = indent + call + '\n'
408 408 lines_after = lines[end_line + 1:]
409 409
410 410 return lines_before + [new_line] + lines_after
411 411
412 412 _help_end_re = re.compile(r"""(%{0,2}
413 413 (?!\d)[\w*]+ # Variable name
414 414 (\.(?!\d)[\w*]+)* # .etc.etc
415 415 )
416 416 (\?\??)$ # ? or ??
417 417 """,
418 418 re.VERBOSE)
419 419
420 420 class HelpEnd(TokenTransformBase):
421 421 """Transformer for help syntax: obj? and obj??"""
422 422 # This needs to be higher priority (lower number) than EscapedCommand so
423 423 # that inspecting magics (%foo?) works.
424 424 priority = 5
425 425
426 426 def __init__(self, start, q_locn):
427 427 super().__init__(start)
428 428 self.q_line = q_locn[0] - 1 # Shift from 1-indexed to 0-indexed
429 429 self.q_col = q_locn[1]
430 430
431 431 @classmethod
432 432 def find(cls, tokens_by_line):
433 433 """Find the first help command (foo?) in the cell.
434 434 """
435 435 for line in tokens_by_line:
436 436 # Last token is NEWLINE; look at last but one
437 437 if len(line) > 2 and line[-2].string == '?':
438 438 # Find the first token that's not INDENT/DEDENT
439 439 ix = 0
440 440 while line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
441 441 ix += 1
442 442 return cls(line[ix].start, line[-2].start)
443 443
444 444 def transform(self, lines):
445 445 """Transform a help command found by the ``find()`` classmethod.
446 446 """
447 447 piece = ''.join(lines[self.start_line:self.q_line+1])
448 448 indent, content = piece[:self.start_col], piece[self.start_col:]
449 449 lines_before = lines[:self.start_line]
450 450 lines_after = lines[self.q_line + 1:]
451 451
452 452 m = _help_end_re.search(content)
453 453 if not m:
454 454 raise SyntaxError(content)
455 455 assert m is not None, content
456 456 target = m.group(1)
457 457 esc = m.group(3)
458 458
459 459 # If we're mid-command, put it back on the next prompt for the user.
460 460 next_input = None
461 461 if (not lines_before) and (not lines_after) \
462 462 and content.strip() != m.group(0):
463 463 next_input = content.rstrip('?\n')
464 464
465 465 call = _make_help_call(target, esc, next_input=next_input)
466 466 new_line = indent + call + '\n'
467 467
468 468 return lines_before + [new_line] + lines_after
469 469
470 470 def make_tokens_by_line(lines:List[str]):
471 471 """Tokenize a series of lines and group tokens by line.
472 472
473 473 The tokens for a multiline Python string or expression are grouped as one
474 474 line. All lines except the last lines should keep their line ending ('\\n',
475 475 '\\r\\n') for this to properly work. Use `.splitlines(keeplineending=True)`
476 476 for example when passing block of text to this function.
477 477
478 478 """
479 479 # NL tokens are used inside multiline expressions, but also after blank
480 480 # lines or comments. This is intentional - see https://bugs.python.org/issue17061
481 481 # We want to group the former case together but split the latter, so we
482 482 # track parentheses level, similar to the internals of tokenize.
483 483 NEWLINE, NL = tokenize.NEWLINE, tokenize.NL
484 484 tokens_by_line = [[]]
485 485 if len(lines) > 1 and not lines[0].endswith(('\n', '\r', '\r\n', '\x0b', '\x0c')):
486 486 warnings.warn("`make_tokens_by_line` received a list of lines which do not have lineending markers ('\\n', '\\r', '\\r\\n', '\\x0b', '\\x0c'), behavior will be unspecified")
487 487 parenlev = 0
488 488 try:
489 489 for token in tokenize.generate_tokens(iter(lines).__next__):
490 490 tokens_by_line[-1].append(token)
491 491 if (token.type == NEWLINE) \
492 492 or ((token.type == NL) and (parenlev <= 0)):
493 493 tokens_by_line.append([])
494 494 elif token.string in {'(', '[', '{'}:
495 495 parenlev += 1
496 496 elif token.string in {')', ']', '}'}:
497 497 if parenlev > 0:
498 498 parenlev -= 1
499 499 except tokenize.TokenError:
500 500 # Input ended in a multiline string or expression. That's OK for us.
501 501 pass
502 502
503 503
504 504 if not tokens_by_line[-1]:
505 505 tokens_by_line.pop()
506 506
507 507
508 508 return tokens_by_line
509 509
510 510 def show_linewise_tokens(s: str):
511 511 """For investigation and debugging"""
512 512 if not s.endswith('\n'):
513 513 s += '\n'
514 514 lines = s.splitlines(keepends=True)
515 515 for line in make_tokens_by_line(lines):
516 516 print("Line -------")
517 517 for tokinfo in line:
518 518 print(" ", tokinfo)
519 519
520 520 # Arbitrary limit to prevent getting stuck in infinite loops
521 521 TRANSFORM_LOOP_LIMIT = 500
522 522
523 523 class TransformerManager:
524 524 """Applies various transformations to a cell or code block.
525 525
526 526 The key methods for external use are ``transform_cell()``
527 527 and ``check_complete()``.
528 528 """
529 529 def __init__(self):
530 530 self.cleanup_transforms = [
531 531 leading_empty_lines,
532 532 leading_indent,
533 533 classic_prompt,
534 534 ipython_prompt,
535 535 ]
536 536 self.line_transforms = [
537 537 cell_magic,
538 538 ]
539 539 self.token_transformers = [
540 540 MagicAssign,
541 541 SystemAssign,
542 542 EscapedCommand,
543 543 HelpEnd,
544 544 ]
545 545
546 546 def do_one_token_transform(self, lines):
547 547 """Find and run the transform earliest in the code.
548 548
549 549 Returns (changed, lines).
550 550
551 551 This method is called repeatedly until changed is False, indicating
552 552 that all available transformations are complete.
553 553
554 554 The tokens following IPython special syntax might not be valid, so
555 555 the transformed code is retokenised every time to identify the next
556 556 piece of special syntax. Hopefully long code cells are mostly valid
557 557 Python, not using lots of IPython special syntax, so this shouldn't be
558 558 a performance issue.
559 559 """
560 560 tokens_by_line = make_tokens_by_line(lines)
561 561 candidates = []
562 562 for transformer_cls in self.token_transformers:
563 563 transformer = transformer_cls.find(tokens_by_line)
564 564 if transformer:
565 565 candidates.append(transformer)
566 566
567 567 if not candidates:
568 568 # Nothing to transform
569 569 return False, lines
570 570 ordered_transformers = sorted(candidates, key=TokenTransformBase.sortby)
571 571 for transformer in ordered_transformers:
572 572 try:
573 573 return True, transformer.transform(lines)
574 574 except SyntaxError:
575 575 pass
576 576 return False, lines
577 577
578 578 def do_token_transforms(self, lines):
579 579 for _ in range(TRANSFORM_LOOP_LIMIT):
580 580 changed, lines = self.do_one_token_transform(lines)
581 581 if not changed:
582 582 return lines
583 583
584 584 raise RuntimeError("Input transformation still changing after "
585 585 "%d iterations. Aborting." % TRANSFORM_LOOP_LIMIT)
586 586
587 587 def transform_cell(self, cell: str) -> str:
588 588 """Transforms a cell of input code"""
589 589 if not cell.endswith('\n'):
590 590 cell += '\n' # Ensure the cell has a trailing newline
591 591 lines = cell.splitlines(keepends=True)
592 592 for transform in self.cleanup_transforms + self.line_transforms:
593 593 lines = transform(lines)
594 594
595 595 lines = self.do_token_transforms(lines)
596 596 return ''.join(lines)
597 597
598 598 def check_complete(self, cell: str):
599 599 """Return whether a block of code is ready to execute, or should be continued
600 600
601 601 Parameters
602 602 ----------
603 603 source : string
604 604 Python input code, which can be multiline.
605 605
606 606 Returns
607 607 -------
608 608 status : str
609 609 One of 'complete', 'incomplete', or 'invalid' if source is not a
610 610 prefix of valid code.
611 611 indent_spaces : int or None
612 612 The number of spaces by which to indent the next line of code. If
613 613 status is not 'incomplete', this is None.
614 614 """
615 615 # Remember if the lines ends in a new line.
616 616 ends_with_newline = False
617 617 for character in reversed(cell):
618 618 if character == '\n':
619 619 ends_with_newline = True
620 620 break
621 621 elif character.strip():
622 622 break
623 623 else:
624 624 continue
625 625
626 626 if not ends_with_newline:
627 627 # Append an newline for consistent tokenization
628 628 # See https://bugs.python.org/issue33899
629 629 cell += '\n'
630 630
631 631 lines = cell.splitlines(keepends=True)
632 632
633 633 if not lines:
634 634 return 'complete', None
635 635
636 636 if lines[-1].endswith('\\'):
637 637 # Explicit backslash continuation
638 638 return 'incomplete', find_last_indent(lines)
639 639
640 640 try:
641 641 for transform in self.cleanup_transforms:
642 642 if not getattr(transform, 'has_side_effects', False):
643 643 lines = transform(lines)
644 644 except SyntaxError:
645 645 return 'invalid', None
646 646
647 647 if lines[0].startswith('%%'):
648 648 # Special case for cell magics - completion marked by blank line
649 649 if lines[-1].strip():
650 650 return 'incomplete', find_last_indent(lines)
651 651 else:
652 652 return 'complete', None
653 653
654 654 try:
655 655 for transform in self.line_transforms:
656 656 if not getattr(transform, 'has_side_effects', False):
657 657 lines = transform(lines)
658 658 lines = self.do_token_transforms(lines)
659 659 except SyntaxError:
660 660 return 'invalid', None
661 661
662 662 tokens_by_line = make_tokens_by_line(lines)
663 663
664 664 if not tokens_by_line:
665 665 return 'incomplete', find_last_indent(lines)
666 666
667 667 if tokens_by_line[-1][-1].type != tokenize.ENDMARKER:
668 668 # We're in a multiline string or expression
669 669 return 'incomplete', find_last_indent(lines)
670 670
671 671 newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER}
672 672
673 673 # Pop the last line which only contains DEDENTs and ENDMARKER
674 674 last_token_line = None
675 675 if {t.type for t in tokens_by_line[-1]} in [
676 676 {tokenize.DEDENT, tokenize.ENDMARKER},
677 677 {tokenize.ENDMARKER}
678 678 ] and len(tokens_by_line) > 1:
679 679 last_token_line = tokens_by_line.pop()
680 680
681 681 while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types:
682 682 tokens_by_line[-1].pop()
683 683
684 684 if not tokens_by_line[-1]:
685 685 return 'incomplete', find_last_indent(lines)
686 686
687 687 if tokens_by_line[-1][-1].string == ':':
688 688 # The last line starts a block (e.g. 'if foo:')
689 689 ix = 0
690 690 while tokens_by_line[-1][ix].type in {tokenize.INDENT, tokenize.DEDENT}:
691 691 ix += 1
692 692
693 693 indent = tokens_by_line[-1][ix].start[1]
694 694 return 'incomplete', indent + 4
695 695
696 696 if tokens_by_line[-1][0].line.endswith('\\'):
697 697 return 'incomplete', None
698 698
699 699 # At this point, our checks think the code is complete (or invalid).
700 700 # We'll use codeop.compile_command to check this with the real parser
701 701 try:
702 702 with warnings.catch_warnings():
703 703 warnings.simplefilter('error', SyntaxWarning)
704 704 res = compile_command(''.join(lines), symbol='exec')
705 705 except (SyntaxError, OverflowError, ValueError, TypeError,
706 706 MemoryError, SyntaxWarning):
707 707 return 'invalid', None
708 708 else:
709 709 if res is None:
710 710 return 'incomplete', find_last_indent(lines)
711 711
712 712 if last_token_line and last_token_line[0].type == tokenize.DEDENT:
713 713 if ends_with_newline:
714 714 return 'complete', None
715 715 return 'incomplete', find_last_indent(lines)
716 716
717 717 # If there's a blank line at the end, assume we're ready to execute
718 718 if not lines[-1].strip():
719 719 return 'complete', None
720 720
721 721 return 'complete', None
722 722
723 723
724 724 def find_last_indent(lines):
725 725 m = _indent_re.match(lines[-1])
726 726 if not m:
727 727 return 0
728 728 return len(m.group(0).replace('\t', ' '*4))
729 729
730 730
731 731 class MaybeAsyncCompile(Compile):
732 732 def __init__(self, extra_flags=0):
733 733 super().__init__()
734 734 self.flags |= extra_flags
735 735
736 def __call__(self, *args, **kwds):
737 return compile(*args, **kwds)
736
737 if sys.version_info < (3,8):
738 def __call__(self, *args, **kwds):
739 return compile(*args, **kwds)
738 740
739 741
740 742 class MaybeAsyncCommandCompiler(CommandCompiler):
741 743 def __init__(self, extra_flags=0):
742 744 self.compiler = MaybeAsyncCompile(extra_flags=extra_flags)
743 745
744 746
745 747 if (sys.version_info.major, sys.version_info.minor) >= (3, 8):
746 748 _extra_flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
747 749 else:
748 750 _extra_flags = ast.PyCF_ONLY_AST
749 751
750 752 compile_command = MaybeAsyncCommandCompiler(extra_flags=_extra_flags)
@@ -1,749 +1,749 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 import os
15 15 import re
16 16 import sys
17 17 from getopt import getopt, GetoptError
18 18
19 19 from traitlets.config.configurable import Configurable
20 20 from . import oinspect
21 21 from .error import UsageError
22 22 from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
23 23 from decorator import decorator
24 24 from ..utils.ipstruct import Struct
25 25 from ..utils.process import arg_split
26 26 from ..utils.text import dedent
27 27 from traitlets import Bool, Dict, Instance, observe
28 28 from logging import error
29 29
30 30 #-----------------------------------------------------------------------------
31 31 # Globals
32 32 #-----------------------------------------------------------------------------
33 33
34 34 # A dict we'll use for each class that has magics, used as temporary storage to
35 35 # pass information between the @line/cell_magic method decorators and the
36 36 # @magics_class class decorator, because the method decorators have no
37 37 # access to the class when they run. See for more details:
38 38 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
39 39
40 40 magics = dict(line={}, cell={})
41 41
42 42 magic_kinds = ('line', 'cell')
43 43 magic_spec = ('line', 'cell', 'line_cell')
44 44 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
45 45
46 46 #-----------------------------------------------------------------------------
47 47 # Utility classes and functions
48 48 #-----------------------------------------------------------------------------
49 49
50 50 class Bunch: pass
51 51
52 52
53 53 def on_off(tag):
54 54 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
55 55 return ['OFF','ON'][tag]
56 56
57 57
58 58 def compress_dhist(dh):
59 59 """Compress a directory history into a new one with at most 20 entries.
60 60
61 61 Return a new list made from the first and last 10 elements of dhist after
62 62 removal of duplicates.
63 63 """
64 64 head, tail = dh[:-10], dh[-10:]
65 65
66 66 newhead = []
67 67 done = set()
68 68 for h in head:
69 69 if h in done:
70 70 continue
71 71 newhead.append(h)
72 72 done.add(h)
73 73
74 74 return newhead + tail
75 75
76 76
77 77 def needs_local_scope(func):
78 78 """Decorator to mark magic functions which need to local scope to run."""
79 79 func.needs_local_scope = True
80 80 return func
81 81
82 82 #-----------------------------------------------------------------------------
83 83 # Class and method decorators for registering magics
84 84 #-----------------------------------------------------------------------------
85 85
86 86 def magics_class(cls):
87 87 """Class decorator for all subclasses of the main Magics class.
88 88
89 89 Any class that subclasses Magics *must* also apply this decorator, to
90 90 ensure that all the methods that have been decorated as line/cell magics
91 91 get correctly registered in the class instance. This is necessary because
92 92 when method decorators run, the class does not exist yet, so they
93 93 temporarily store their information into a module global. Application of
94 94 this class decorator copies that global data to the class instance and
95 95 clears the global.
96 96
97 97 Obviously, this mechanism is not thread-safe, which means that the
98 98 *creation* of subclasses of Magic should only be done in a single-thread
99 99 context. Instantiation of the classes has no restrictions. Given that
100 100 these classes are typically created at IPython startup time and before user
101 101 application code becomes active, in practice this should not pose any
102 102 problems.
103 103 """
104 104 cls.registered = True
105 105 cls.magics = dict(line = magics['line'],
106 106 cell = magics['cell'])
107 107 magics['line'] = {}
108 108 magics['cell'] = {}
109 109 return cls
110 110
111 111
112 112 def record_magic(dct, magic_kind, magic_name, func):
113 113 """Utility function to store a function as a magic of a specific kind.
114 114
115 115 Parameters
116 116 ----------
117 117 dct : dict
118 118 A dictionary with 'line' and 'cell' subdicts.
119 119
120 120 magic_kind : str
121 121 Kind of magic to be stored.
122 122
123 123 magic_name : str
124 124 Key to store the magic as.
125 125
126 126 func : function
127 127 Callable object to store.
128 128 """
129 129 if magic_kind == 'line_cell':
130 130 dct['line'][magic_name] = dct['cell'][magic_name] = func
131 131 else:
132 132 dct[magic_kind][magic_name] = func
133 133
134 134
135 135 def validate_type(magic_kind):
136 136 """Ensure that the given magic_kind is valid.
137 137
138 138 Check that the given magic_kind is one of the accepted spec types (stored
139 139 in the global `magic_spec`), raise ValueError otherwise.
140 140 """
141 141 if magic_kind not in magic_spec:
142 142 raise ValueError('magic_kind must be one of %s, %s given' %
143 143 magic_kinds, magic_kind)
144 144
145 145
146 146 # The docstrings for the decorator below will be fairly similar for the two
147 147 # types (method and function), so we generate them here once and reuse the
148 148 # templates below.
149 149 _docstring_template = \
150 150 """Decorate the given {0} as {1} magic.
151 151
152 152 The decorator can be used with or without arguments, as follows.
153 153
154 154 i) without arguments: it will create a {1} magic named as the {0} being
155 155 decorated::
156 156
157 157 @deco
158 158 def foo(...)
159 159
160 160 will create a {1} magic named `foo`.
161 161
162 162 ii) with one string argument: which will be used as the actual name of the
163 163 resulting magic::
164 164
165 165 @deco('bar')
166 166 def foo(...)
167 167
168 168 will create a {1} magic named `bar`.
169 169
170 170 To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
171 171 """
172 172
173 173 # These two are decorator factories. While they are conceptually very similar,
174 174 # there are enough differences in the details that it's simpler to have them
175 175 # written as completely standalone functions rather than trying to share code
176 176 # and make a single one with convoluted logic.
177 177
178 178 def _method_magic_marker(magic_kind):
179 179 """Decorator factory for methods in Magics subclasses.
180 180 """
181 181
182 182 validate_type(magic_kind)
183 183
184 184 # This is a closure to capture the magic_kind. We could also use a class,
185 185 # but it's overkill for just that one bit of state.
186 186 def magic_deco(arg):
187 187 call = lambda f, *a, **k: f(*a, **k)
188 188
189 189 if callable(arg):
190 190 # "Naked" decorator call (just @foo, no args)
191 191 func = arg
192 192 name = func.__name__
193 193 retval = decorator(call, func)
194 194 record_magic(magics, magic_kind, name, name)
195 195 elif isinstance(arg, str):
196 196 # Decorator called with arguments (@foo('bar'))
197 197 name = arg
198 198 def mark(func, *a, **kw):
199 199 record_magic(magics, magic_kind, name, func.__name__)
200 200 return decorator(call, func)
201 201 retval = mark
202 202 else:
203 203 raise TypeError("Decorator can only be called with "
204 204 "string or function")
205 205 return retval
206 206
207 207 # Ensure the resulting decorator has a usable docstring
208 208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
209 209 return magic_deco
210 210
211 211
212 212 def _function_magic_marker(magic_kind):
213 213 """Decorator factory for standalone functions.
214 214 """
215 215 validate_type(magic_kind)
216 216
217 217 # This is a closure to capture the magic_kind. We could also use a class,
218 218 # but it's overkill for just that one bit of state.
219 219 def magic_deco(arg):
220 220 call = lambda f, *a, **k: f(*a, **k)
221 221
222 222 # Find get_ipython() in the caller's namespace
223 223 caller = sys._getframe(1)
224 224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 225 get_ipython = getattr(caller, ns).get('get_ipython')
226 226 if get_ipython is not None:
227 227 break
228 228 else:
229 229 raise NameError('Decorator can only run in context where '
230 230 '`get_ipython` exists')
231 231
232 232 ip = get_ipython()
233 233
234 234 if callable(arg):
235 235 # "Naked" decorator call (just @foo, no args)
236 236 func = arg
237 237 name = func.__name__
238 238 ip.register_magic_function(func, magic_kind, name)
239 239 retval = decorator(call, func)
240 240 elif isinstance(arg, str):
241 241 # Decorator called with arguments (@foo('bar'))
242 242 name = arg
243 243 def mark(func, *a, **kw):
244 244 ip.register_magic_function(func, magic_kind, name)
245 245 return decorator(call, func)
246 246 retval = mark
247 247 else:
248 248 raise TypeError("Decorator can only be called with "
249 249 "string or function")
250 250 return retval
251 251
252 252 # Ensure the resulting decorator has a usable docstring
253 253 ds = _docstring_template.format('function', magic_kind)
254 254
255 255 ds += dedent("""
256 256 Note: this decorator can only be used in a context where IPython is already
257 257 active, so that the `get_ipython()` call succeeds. You can therefore use
258 258 it in your startup files loaded after IPython initializes, but *not* in the
259 259 IPython configuration file itself, which is executed before IPython is
260 260 fully up and running. Any file located in the `startup` subdirectory of
261 261 your configuration profile will be OK in this sense.
262 262 """)
263 263
264 264 magic_deco.__doc__ = ds
265 265 return magic_deco
266 266
267 267
268 268 MAGIC_NO_VAR_EXPAND_ATTR = '_ipython_magic_no_var_expand'
269 269
270 270
271 271 def no_var_expand(magic_func):
272 272 """Mark a magic function as not needing variable expansion
273 273
274 274 By default, IPython interprets `{a}` or `$a` in the line passed to magics
275 275 as variables that should be interpolated from the interactive namespace
276 276 before passing the line to the magic function.
277 277 This is not always desirable, e.g. when the magic executes Python code
278 278 (%timeit, %time, etc.).
279 279 Decorate magics with `@no_var_expand` to opt-out of variable expansion.
280 280
281 281 .. versionadded:: 7.3
282 282 """
283 283 setattr(magic_func, MAGIC_NO_VAR_EXPAND_ATTR, True)
284 284 return magic_func
285 285
286 286
287 287 # Create the actual decorators for public use
288 288
289 289 # These three are used to decorate methods in class definitions
290 290 line_magic = _method_magic_marker('line')
291 291 cell_magic = _method_magic_marker('cell')
292 292 line_cell_magic = _method_magic_marker('line_cell')
293 293
294 294 # These three decorate standalone functions and perform the decoration
295 295 # immediately. They can only run where get_ipython() works
296 296 register_line_magic = _function_magic_marker('line')
297 297 register_cell_magic = _function_magic_marker('cell')
298 298 register_line_cell_magic = _function_magic_marker('line_cell')
299 299
300 300 #-----------------------------------------------------------------------------
301 301 # Core Magic classes
302 302 #-----------------------------------------------------------------------------
303 303
304 304 class MagicsManager(Configurable):
305 305 """Object that handles all magic-related functionality for IPython.
306 306 """
307 307 # Non-configurable class attributes
308 308
309 309 # A two-level dict, first keyed by magic type, then by magic function, and
310 310 # holding the actual callable object as value. This is the dict used for
311 311 # magic function dispatch
312 312 magics = Dict()
313 313 lazy_magics = Dict(
314 314 help="""
315 315 Mapping from magic names to modules to load.
316 316
317 317 This can be used in IPython/IPykernel configuration to declare lazy magics
318 318 that will only be imported/registered on first use.
319 319
320 320 For example::
321 321
322 c.MagicsManger.lazy_magics = {
322 c.MagicsManager.lazy_magics = {
323 323 "my_magic": "slow.to.import",
324 324 "my_other_magic": "also.slow",
325 325 }
326 326
327 327 On first invocation of `%my_magic`, `%%my_magic`, `%%my_other_magic` or
328 328 `%%my_other_magic`, the corresponding module will be loaded as an ipython
329 329 extensions as if you had previously done `%load_ext ipython`.
330 330
331 331 Magics names should be without percent(s) as magics can be both cell
332 332 and line magics.
333 333
334 334 Lazy loading happen relatively late in execution process, and
335 335 complex extensions that manipulate Python/IPython internal state or global state
336 336 might not support lazy loading.
337 337 """
338 338 ).tag(
339 339 config=True,
340 340 )
341 341
342 342 # A registry of the original objects that we've been given holding magics.
343 343 registry = Dict()
344 344
345 345 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
346 346
347 347 auto_magic = Bool(True, help=
348 348 "Automatically call line magics without requiring explicit % prefix"
349 349 ).tag(config=True)
350 350 @observe('auto_magic')
351 351 def _auto_magic_changed(self, change):
352 352 self.shell.automagic = change['new']
353 353
354 354 _auto_status = [
355 355 'Automagic is OFF, % prefix IS needed for line magics.',
356 356 'Automagic is ON, % prefix IS NOT needed for line magics.']
357 357
358 358 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
359 359
360 360 def __init__(self, shell=None, config=None, user_magics=None, **traits):
361 361
362 362 super(MagicsManager, self).__init__(shell=shell, config=config,
363 363 user_magics=user_magics, **traits)
364 364 self.magics = dict(line={}, cell={})
365 365 # Let's add the user_magics to the registry for uniformity, so *all*
366 366 # registered magic containers can be found there.
367 367 self.registry[user_magics.__class__.__name__] = user_magics
368 368
369 369 def auto_status(self):
370 370 """Return descriptive string with automagic status."""
371 371 return self._auto_status[self.auto_magic]
372 372
373 373 def lsmagic(self):
374 374 """Return a dict of currently available magic functions.
375 375
376 376 The return dict has the keys 'line' and 'cell', corresponding to the
377 377 two types of magics we support. Each value is a list of names.
378 378 """
379 379 return self.magics
380 380
381 381 def lsmagic_docs(self, brief=False, missing=''):
382 382 """Return dict of documentation of magic functions.
383 383
384 384 The return dict has the keys 'line' and 'cell', corresponding to the
385 385 two types of magics we support. Each value is a dict keyed by magic
386 386 name whose value is the function docstring. If a docstring is
387 387 unavailable, the value of `missing` is used instead.
388 388
389 389 If brief is True, only the first line of each docstring will be returned.
390 390 """
391 391 docs = {}
392 392 for m_type in self.magics:
393 393 m_docs = {}
394 394 for m_name, m_func in self.magics[m_type].items():
395 395 if m_func.__doc__:
396 396 if brief:
397 397 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
398 398 else:
399 399 m_docs[m_name] = m_func.__doc__.rstrip()
400 400 else:
401 401 m_docs[m_name] = missing
402 402 docs[m_type] = m_docs
403 403 return docs
404 404
405 405 def register_lazy(self, name: str, fully_qualified_name: str):
406 406 """
407 407 Lazily register a magic via an extension.
408 408
409 409
410 410 Parameters
411 411 ----------
412 412 name : str
413 413 Name of the magic you wish to register.
414 414 fully_qualified_name :
415 415 Fully qualified name of the module/submodule that should be loaded
416 416 as an extensions when the magic is first called.
417 417 It is assumed that loading this extensions will register the given
418 418 magic.
419 419 """
420 420
421 421 self.lazy_magics[name] = fully_qualified_name
422 422
423 423 def register(self, *magic_objects):
424 424 """Register one or more instances of Magics.
425 425
426 426 Take one or more classes or instances of classes that subclass the main
427 427 `core.Magic` class, and register them with IPython to use the magic
428 428 functions they provide. The registration process will then ensure that
429 429 any methods that have decorated to provide line and/or cell magics will
430 430 be recognized with the `%x`/`%%x` syntax as a line/cell magic
431 431 respectively.
432 432
433 433 If classes are given, they will be instantiated with the default
434 434 constructor. If your classes need a custom constructor, you should
435 435 instanitate them first and pass the instance.
436 436
437 437 The provided arguments can be an arbitrary mix of classes and instances.
438 438
439 439 Parameters
440 440 ----------
441 441 magic_objects : one or more classes or instances
442 442 """
443 443 # Start by validating them to ensure they have all had their magic
444 444 # methods registered at the instance level
445 445 for m in magic_objects:
446 446 if not m.registered:
447 447 raise ValueError("Class of magics %r was constructed without "
448 448 "the @register_magics class decorator")
449 449 if isinstance(m, type):
450 450 # If we're given an uninstantiated class
451 451 m = m(shell=self.shell)
452 452
453 453 # Now that we have an instance, we can register it and update the
454 454 # table of callables
455 455 self.registry[m.__class__.__name__] = m
456 456 for mtype in magic_kinds:
457 457 self.magics[mtype].update(m.magics[mtype])
458 458
459 459 def register_function(self, func, magic_kind='line', magic_name=None):
460 460 """Expose a standalone function as magic function for IPython.
461 461
462 462 This will create an IPython magic (line, cell or both) from a
463 463 standalone function. The functions should have the following
464 464 signatures:
465 465
466 466 * For line magics: `def f(line)`
467 467 * For cell magics: `def f(line, cell)`
468 468 * For a function that does both: `def f(line, cell=None)`
469 469
470 470 In the latter case, the function will be called with `cell==None` when
471 471 invoked as `%f`, and with cell as a string when invoked as `%%f`.
472 472
473 473 Parameters
474 474 ----------
475 475 func : callable
476 476 Function to be registered as a magic.
477 477
478 478 magic_kind : str
479 479 Kind of magic, one of 'line', 'cell' or 'line_cell'
480 480
481 481 magic_name : optional str
482 482 If given, the name the magic will have in the IPython namespace. By
483 483 default, the name of the function itself is used.
484 484 """
485 485
486 486 # Create the new method in the user_magics and register it in the
487 487 # global table
488 488 validate_type(magic_kind)
489 489 magic_name = func.__name__ if magic_name is None else magic_name
490 490 setattr(self.user_magics, magic_name, func)
491 491 record_magic(self.magics, magic_kind, magic_name, func)
492 492
493 493 def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None):
494 494 """Register an alias to a magic function.
495 495
496 496 The alias is an instance of :class:`MagicAlias`, which holds the
497 497 name and kind of the magic it should call. Binding is done at
498 498 call time, so if the underlying magic function is changed the alias
499 499 will call the new function.
500 500
501 501 Parameters
502 502 ----------
503 503 alias_name : str
504 504 The name of the magic to be registered.
505 505
506 506 magic_name : str
507 507 The name of an existing magic.
508 508
509 509 magic_kind : str
510 510 Kind of magic, one of 'line' or 'cell'
511 511 """
512 512
513 513 # `validate_type` is too permissive, as it allows 'line_cell'
514 514 # which we do not handle.
515 515 if magic_kind not in magic_kinds:
516 516 raise ValueError('magic_kind must be one of %s, %s given' %
517 517 magic_kinds, magic_kind)
518 518
519 519 alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params)
520 520 setattr(self.user_magics, alias_name, alias)
521 521 record_magic(self.magics, magic_kind, alias_name, alias)
522 522
523 523 # Key base class that provides the central functionality for magics.
524 524
525 525
526 526 class Magics(Configurable):
527 527 """Base class for implementing magic functions.
528 528
529 529 Shell functions which can be reached as %function_name. All magic
530 530 functions should accept a string, which they can parse for their own
531 531 needs. This can make some functions easier to type, eg `%cd ../`
532 532 vs. `%cd("../")`
533 533
534 534 Classes providing magic functions need to subclass this class, and they
535 535 MUST:
536 536
537 537 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
538 538 individual methods as magic functions, AND
539 539
540 540 - Use the class decorator `@magics_class` to ensure that the magic
541 541 methods are properly registered at the instance level upon instance
542 542 initialization.
543 543
544 544 See :mod:`magic_functions` for examples of actual implementation classes.
545 545 """
546 546 # Dict holding all command-line options for each magic.
547 547 options_table = None
548 548 # Dict for the mapping of magic names to methods, set by class decorator
549 549 magics = None
550 550 # Flag to check that the class decorator was properly applied
551 551 registered = False
552 552 # Instance of IPython shell
553 553 shell = None
554 554
555 555 def __init__(self, shell=None, **kwargs):
556 556 if not(self.__class__.registered):
557 557 raise ValueError('Magics subclass without registration - '
558 558 'did you forget to apply @magics_class?')
559 559 if shell is not None:
560 560 if hasattr(shell, 'configurables'):
561 561 shell.configurables.append(self)
562 562 if hasattr(shell, 'config'):
563 563 kwargs.setdefault('parent', shell)
564 564
565 565 self.shell = shell
566 566 self.options_table = {}
567 567 # The method decorators are run when the instance doesn't exist yet, so
568 568 # they can only record the names of the methods they are supposed to
569 569 # grab. Only now, that the instance exists, can we create the proper
570 570 # mapping to bound methods. So we read the info off the original names
571 571 # table and replace each method name by the actual bound method.
572 572 # But we mustn't clobber the *class* mapping, in case of multiple instances.
573 573 class_magics = self.magics
574 574 self.magics = {}
575 575 for mtype in magic_kinds:
576 576 tab = self.magics[mtype] = {}
577 577 cls_tab = class_magics[mtype]
578 578 for magic_name, meth_name in cls_tab.items():
579 579 if isinstance(meth_name, str):
580 580 # it's a method name, grab it
581 581 tab[magic_name] = getattr(self, meth_name)
582 582 else:
583 583 # it's the real thing
584 584 tab[magic_name] = meth_name
585 585 # Configurable **needs** to be initiated at the end or the config
586 586 # magics get screwed up.
587 587 super(Magics, self).__init__(**kwargs)
588 588
589 589 def arg_err(self,func):
590 590 """Print docstring if incorrect arguments were passed"""
591 591 print('Error in arguments:')
592 592 print(oinspect.getdoc(func))
593 593
594 594 def format_latex(self, strng):
595 595 """Format a string for latex inclusion."""
596 596
597 597 # Characters that need to be escaped for latex:
598 598 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
599 599 # Magic command names as headers:
600 600 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
601 601 re.MULTILINE)
602 602 # Magic commands
603 603 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
604 604 re.MULTILINE)
605 605 # Paragraph continue
606 606 par_re = re.compile(r'\\$',re.MULTILINE)
607 607
608 608 # The "\n" symbol
609 609 newline_re = re.compile(r'\\n')
610 610
611 611 # Now build the string for output:
612 612 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
613 613 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
614 614 strng)
615 615 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
616 616 strng = par_re.sub(r'\\\\',strng)
617 617 strng = escape_re.sub(r'\\\1',strng)
618 618 strng = newline_re.sub(r'\\textbackslash{}n',strng)
619 619 return strng
620 620
621 621 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
622 622 """Parse options passed to an argument string.
623 623
624 624 The interface is similar to that of :func:`getopt.getopt`, but it
625 625 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
626 626 and the stripped argument string still as a string.
627 627
628 628 arg_str is quoted as a true sys.argv vector by using shlex.split.
629 629 This allows us to easily expand variables, glob files, quote
630 630 arguments, etc.
631 631
632 632 Parameters
633 633 ----------
634 634
635 635 arg_str : str
636 636 The arguments to parse.
637 637
638 638 opt_str : str
639 639 The options specification.
640 640
641 641 mode : str, default 'string'
642 642 If given as 'list', the argument string is returned as a list (split
643 643 on whitespace) instead of a string.
644 644
645 645 list_all : bool, default False
646 646 Put all option values in lists. Normally only options
647 647 appearing more than once are put in a list.
648 648
649 649 posix : bool, default True
650 650 Whether to split the input line in POSIX mode or not, as per the
651 651 conventions outlined in the :mod:`shlex` module from the standard
652 652 library.
653 653 """
654 654
655 655 # inject default options at the beginning of the input line
656 656 caller = sys._getframe(1).f_code.co_name
657 657 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
658 658
659 659 mode = kw.get('mode','string')
660 660 if mode not in ['string','list']:
661 661 raise ValueError('incorrect mode given: %s' % mode)
662 662 # Get options
663 663 list_all = kw.get('list_all',0)
664 664 posix = kw.get('posix', os.name == 'posix')
665 665 strict = kw.get('strict', True)
666 666
667 667 # Check if we have more than one argument to warrant extra processing:
668 668 odict = {} # Dictionary with options
669 669 args = arg_str.split()
670 670 if len(args) >= 1:
671 671 # If the list of inputs only has 0 or 1 thing in it, there's no
672 672 # need to look for options
673 673 argv = arg_split(arg_str, posix, strict)
674 674 # Do regular option processing
675 675 try:
676 676 opts,args = getopt(argv, opt_str, long_opts)
677 677 except GetoptError as e:
678 678 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
679 679 " ".join(long_opts)))
680 680 for o,a in opts:
681 681 if o.startswith('--'):
682 682 o = o[2:]
683 683 else:
684 684 o = o[1:]
685 685 try:
686 686 odict[o].append(a)
687 687 except AttributeError:
688 688 odict[o] = [odict[o],a]
689 689 except KeyError:
690 690 if list_all:
691 691 odict[o] = [a]
692 692 else:
693 693 odict[o] = a
694 694
695 695 # Prepare opts,args for return
696 696 opts = Struct(odict)
697 697 if mode == 'string':
698 698 args = ' '.join(args)
699 699
700 700 return opts,args
701 701
702 702 def default_option(self, fn, optstr):
703 703 """Make an entry in the options_table for fn, with value optstr"""
704 704
705 705 if fn not in self.lsmagic():
706 706 error("%s is not a magic function" % fn)
707 707 self.options_table[fn] = optstr
708 708
709 709
710 710 class MagicAlias(object):
711 711 """An alias to another magic function.
712 712
713 713 An alias is determined by its magic name and magic kind. Lookup
714 714 is done at call time, so if the underlying magic changes the alias
715 715 will call the new function.
716 716
717 717 Use the :meth:`MagicsManager.register_alias` method or the
718 718 `%alias_magic` magic function to create and register a new alias.
719 719 """
720 720 def __init__(self, shell, magic_name, magic_kind, magic_params=None):
721 721 self.shell = shell
722 722 self.magic_name = magic_name
723 723 self.magic_params = magic_params
724 724 self.magic_kind = magic_kind
725 725
726 726 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
727 727 self.__doc__ = "Alias for `%s`." % self.pretty_target
728 728
729 729 self._in_call = False
730 730
731 731 def __call__(self, *args, **kwargs):
732 732 """Call the magic alias."""
733 733 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
734 734 if fn is None:
735 735 raise UsageError("Magic `%s` not found." % self.pretty_target)
736 736
737 737 # Protect against infinite recursion.
738 738 if self._in_call:
739 739 raise UsageError("Infinite recursion detected; "
740 740 "magic aliases cannot call themselves.")
741 741 self._in_call = True
742 742 try:
743 743 if self.magic_params:
744 744 args_list = list(args)
745 745 args_list[0] = self.magic_params + " " + args[0]
746 746 args = tuple(args_list)
747 747 return fn(*args, **kwargs)
748 748 finally:
749 749 self._in_call = False
@@ -1,579 +1,580 b''
1 1 """Tests for debugging machinery.
2 2 """
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import bdb
8 8 import builtins
9 9 import os
10 10 import signal
11 11 import subprocess
12 12 import sys
13 13 import time
14 14 import warnings
15 15
16 16 from subprocess import PIPE, CalledProcessError, check_output
17 17 from tempfile import NamedTemporaryFile
18 18 from textwrap import dedent
19 19 from unittest.mock import patch
20 20
21 21 import nose.tools as nt
22 22
23 23 from IPython.core import debugger
24 24 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
25 25 from IPython.testing.decorators import skip_win32
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Helper classes, from CPython's Pdb test suite
29 29 #-----------------------------------------------------------------------------
30 30
31 31 class _FakeInput(object):
32 32 """
33 33 A fake input stream for pdb's interactive debugger. Whenever a
34 34 line is read, print it (to simulate the user typing it), and then
35 35 return it. The set of lines to return is specified in the
36 36 constructor; they should not have trailing newlines.
37 37 """
38 38 def __init__(self, lines):
39 39 self.lines = iter(lines)
40 40
41 41 def readline(self):
42 42 line = next(self.lines)
43 43 print(line)
44 44 return line+'\n'
45 45
46 46 class PdbTestInput(object):
47 47 """Context manager that makes testing Pdb in doctests easier."""
48 48
49 49 def __init__(self, input):
50 50 self.input = input
51 51
52 52 def __enter__(self):
53 53 self.real_stdin = sys.stdin
54 54 sys.stdin = _FakeInput(self.input)
55 55
56 56 def __exit__(self, *exc):
57 57 sys.stdin = self.real_stdin
58 58
59 59 #-----------------------------------------------------------------------------
60 60 # Tests
61 61 #-----------------------------------------------------------------------------
62 62
63 63 def test_longer_repr():
64 64 try:
65 65 from reprlib import repr as trepr # Py 3
66 66 except ImportError:
67 67 from repr import repr as trepr # Py 2
68 68
69 69 a = '1234567890'* 7
70 70 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
71 71 a_trunc = "'123456789012...8901234567890'"
72 72 nt.assert_equal(trepr(a), a_trunc)
73 73 # The creation of our tracer modifies the repr module's repr function
74 74 # in-place, since that global is used directly by the stdlib's pdb module.
75 75 with warnings.catch_warnings():
76 76 warnings.simplefilter('ignore', DeprecationWarning)
77 77 debugger.Tracer()
78 78 nt.assert_equal(trepr(a), ar)
79 79
80 80 def test_ipdb_magics():
81 81 '''Test calling some IPython magics from ipdb.
82 82
83 83 First, set up some test functions and classes which we can inspect.
84 84
85 85 >>> class ExampleClass(object):
86 86 ... """Docstring for ExampleClass."""
87 87 ... def __init__(self):
88 88 ... """Docstring for ExampleClass.__init__"""
89 89 ... pass
90 90 ... def __str__(self):
91 91 ... return "ExampleClass()"
92 92
93 93 >>> def example_function(x, y, z="hello"):
94 94 ... """Docstring for example_function."""
95 95 ... pass
96 96
97 97 >>> old_trace = sys.gettrace()
98 98
99 99 Create a function which triggers ipdb.
100 100
101 101 >>> def trigger_ipdb():
102 102 ... a = ExampleClass()
103 103 ... debugger.Pdb().set_trace()
104 104
105 105 >>> with PdbTestInput([
106 106 ... 'pdef example_function',
107 107 ... 'pdoc ExampleClass',
108 108 ... 'up',
109 109 ... 'down',
110 110 ... 'list',
111 111 ... 'pinfo a',
112 112 ... 'll',
113 113 ... 'continue',
114 114 ... ]):
115 115 ... trigger_ipdb()
116 116 --Return--
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> pdef example_function
124 124 example_function(x, y, z='hello')
125 125 ipdb> pdoc ExampleClass
126 126 Class docstring:
127 127 Docstring for ExampleClass.
128 128 Init docstring:
129 129 Docstring for ExampleClass.__init__
130 130 ipdb> up
131 131 > <doctest ...>(11)<module>()
132 132 7 'pinfo a',
133 133 8 'll',
134 134 9 'continue',
135 135 10 ]):
136 136 ---> 11 trigger_ipdb()
137 137 <BLANKLINE>
138 138 ipdb> down
139 139 None
140 140 > <doctest ...>(3)trigger_ipdb()
141 141 1 def trigger_ipdb():
142 142 2 a = ExampleClass()
143 143 ----> 3 debugger.Pdb().set_trace()
144 144 <BLANKLINE>
145 145 ipdb> list
146 146 1 def trigger_ipdb():
147 147 2 a = ExampleClass()
148 148 ----> 3 debugger.Pdb().set_trace()
149 149 <BLANKLINE>
150 150 ipdb> pinfo a
151 151 Type: ExampleClass
152 152 String form: ExampleClass()
153 153 Namespace: Local...
154 154 Docstring: Docstring for ExampleClass.
155 155 Init docstring: Docstring for ExampleClass.__init__
156 156 ipdb> ll
157 157 1 def trigger_ipdb():
158 158 2 a = ExampleClass()
159 159 ----> 3 debugger.Pdb().set_trace()
160 160 <BLANKLINE>
161 161 ipdb> continue
162 162
163 163 Restore previous trace function, e.g. for coverage.py
164 164
165 165 >>> sys.settrace(old_trace)
166 166 '''
167 167
168 168 def test_ipdb_magics2():
169 169 '''Test ipdb with a very short function.
170 170
171 171 >>> old_trace = sys.gettrace()
172 172
173 173 >>> def bar():
174 174 ... pass
175 175
176 176 Run ipdb.
177 177
178 178 >>> with PdbTestInput([
179 179 ... 'continue',
180 180 ... ]):
181 181 ... debugger.Pdb().runcall(bar)
182 182 > <doctest ...>(2)bar()
183 183 1 def bar():
184 184 ----> 2 pass
185 185 <BLANKLINE>
186 186 ipdb> continue
187 187
188 188 Restore previous trace function, e.g. for coverage.py
189 189
190 190 >>> sys.settrace(old_trace)
191 191 '''
192 192
193 193 def can_quit():
194 194 '''Test that quit work in ipydb
195 195
196 196 >>> old_trace = sys.gettrace()
197 197
198 198 >>> def bar():
199 199 ... pass
200 200
201 201 >>> with PdbTestInput([
202 202 ... 'quit',
203 203 ... ]):
204 204 ... debugger.Pdb().runcall(bar)
205 205 > <doctest ...>(2)bar()
206 206 1 def bar():
207 207 ----> 2 pass
208 208 <BLANKLINE>
209 209 ipdb> quit
210 210
211 211 Restore previous trace function, e.g. for coverage.py
212 212
213 213 >>> sys.settrace(old_trace)
214 214 '''
215 215
216 216
217 217 def can_exit():
218 218 '''Test that quit work in ipydb
219 219
220 220 >>> old_trace = sys.gettrace()
221 221
222 222 >>> def bar():
223 223 ... pass
224 224
225 225 >>> with PdbTestInput([
226 226 ... 'exit',
227 227 ... ]):
228 228 ... debugger.Pdb().runcall(bar)
229 229 > <doctest ...>(2)bar()
230 230 1 def bar():
231 231 ----> 2 pass
232 232 <BLANKLINE>
233 233 ipdb> exit
234 234
235 235 Restore previous trace function, e.g. for coverage.py
236 236
237 237 >>> sys.settrace(old_trace)
238 238 '''
239 239
240 240
241 241 def test_interruptible_core_debugger():
242 242 """The debugger can be interrupted.
243 243
244 244 The presumption is there is some mechanism that causes a KeyboardInterrupt
245 245 (this is implemented in ipykernel). We want to ensure the
246 246 KeyboardInterrupt cause debugging to cease.
247 247 """
248 248 def raising_input(msg="", called=[0]):
249 249 called[0] += 1
250 250 if called[0] == 1:
251 251 raise KeyboardInterrupt()
252 252 else:
253 253 raise AssertionError("input() should only be called once!")
254 254
255 255 with patch.object(builtins, "input", raising_input):
256 256 debugger.InterruptiblePdb().set_trace()
257 257 # The way this test will fail is by set_trace() never exiting,
258 258 # resulting in a timeout by the test runner. The alternative
259 259 # implementation would involve a subprocess, but that adds issues with
260 260 # interrupting subprocesses that are rather complex, so it's simpler
261 261 # just to do it this way.
262 262
263 263 @skip_win32
264 264 def test_xmode_skip():
265 265 """that xmode skip frames
266 266
267 267 Not as a doctest as pytest does not run doctests.
268 268 """
269 269 import pexpect
270 270 env = os.environ.copy()
271 271 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
272 272
273 273 child = pexpect.spawn(
274 274 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
275 275 )
276 276 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
277 277
278 278 child.expect("IPython")
279 279 child.expect("\n")
280 280 child.expect_exact("In [1]")
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 raise ValueError
290 290
291 291 f()
292 292 """
293 293 )
294 294
295 295 for line in block.splitlines():
296 296 child.sendline(line)
297 297 child.expect_exact(line)
298 298 child.expect_exact("skipping")
299 299
300 300 block = dedent(
301 301 """
302 302 def f():
303 303 __tracebackhide__ = True
304 304 g()
305 305
306 306 def g():
307 307 from IPython.core.debugger import set_trace
308 308 set_trace()
309 309
310 310 f()
311 311 """
312 312 )
313 313
314 314 for line in block.splitlines():
315 315 child.sendline(line)
316 316 child.expect_exact(line)
317 317
318 318 child.expect("ipdb>")
319 319 child.sendline("w")
320 320 child.expect("hidden")
321 321 child.expect("ipdb>")
322 322 child.sendline("skip_hidden false")
323 323 child.sendline("w")
324 324 child.expect("__traceba")
325 325 child.expect("ipdb>")
326 326
327 327 child.close()
328 328
329 329
330 330 skip_decorators_blocks = (
331 331 """
332 332 def helpers_helper():
333 333 pass # should not stop here except breakpoint
334 334 """,
335 335 """
336 336 def helper_1():
337 337 helpers_helper() # should not stop here
338 338 """,
339 339 """
340 340 def helper_2():
341 341 pass # should not stop here
342 342 """,
343 343 """
344 344 def pdb_skipped_decorator2(function):
345 345 def wrapped_fn(*args, **kwargs):
346 346 __debuggerskip__ = True
347 347 helper_2()
348 348 __debuggerskip__ = False
349 349 result = function(*args, **kwargs)
350 350 __debuggerskip__ = True
351 351 helper_2()
352 352 return result
353 353 return wrapped_fn
354 354 """,
355 355 """
356 356 def pdb_skipped_decorator(function):
357 357 def wrapped_fn(*args, **kwargs):
358 358 __debuggerskip__ = True
359 359 helper_1()
360 360 __debuggerskip__ = False
361 361 result = function(*args, **kwargs)
362 362 __debuggerskip__ = True
363 363 helper_2()
364 364 return result
365 365 return wrapped_fn
366 366 """,
367 367 """
368 368 @pdb_skipped_decorator
369 369 @pdb_skipped_decorator2
370 370 def bar(x, y):
371 371 return x * y
372 372 """,
373 373 """import IPython.terminal.debugger as ipdb""",
374 374 """
375 375 def f():
376 376 ipdb.set_trace()
377 377 bar(3, 4)
378 378 """,
379 379 """
380 380 f()
381 381 """,
382 382 )
383 383
384 384
385 385 def _decorator_skip_setup():
386 386 import pexpect
387 387
388 388 env = os.environ.copy()
389 389 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
390 390
391 391 child = pexpect.spawn(
392 392 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
393 393 )
394 child.str_last_chars = 1000
394 395 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
395 396
396 397 child.expect("IPython")
397 398 child.expect("\n")
398 399
399 400 dedented_blocks = [dedent(b).strip() for b in skip_decorators_blocks]
400 401 in_prompt_number = 1
401 402 for cblock in dedented_blocks:
402 403 child.expect_exact(f"In [{in_prompt_number}]:")
403 404 in_prompt_number += 1
404 405 for line in cblock.splitlines():
405 406 child.sendline(line)
406 407 child.expect_exact(line)
407 408 child.sendline("")
408 409 return child
409 410
410 411
411 412 @skip_win32
412 413 def test_decorator_skip():
413 414 """test that decorator frames can be skipped."""
414 415
415 416 child = _decorator_skip_setup()
416 417
417 418 child.expect_exact("3 bar(3, 4)")
418 419 child.expect("ipdb>")
419 420
420 421 child.expect("ipdb>")
421 422 child.sendline("step")
422 423 child.expect_exact("step")
423 424
424 425 child.expect_exact("1 @pdb_skipped_decorator")
425 426
426 427 child.sendline("s")
427 428 child.expect_exact("return x * y")
428 429
429 430 child.close()
430 431
431 432
432 433 @skip_win32
433 434 def test_decorator_skip_disabled():
434 435 """test that decorator frame skipping can be disabled"""
435 436
436 437 child = _decorator_skip_setup()
437 438
438 439 child.expect_exact("3 bar(3, 4)")
439 440
440 441 for input_, expected in [
441 442 ("skip_predicates debuggerskip False", ""),
442 443 ("skip_predicates", "debuggerskip : False"),
443 444 ("step", "---> 2 def wrapped_fn"),
444 445 ("step", "----> 3 __debuggerskip__"),
445 446 ("step", "----> 4 helper_1()"),
446 447 ("step", "---> 1 def helper_1():"),
447 448 ("next", "----> 2 helpers_helper()"),
448 449 ("next", "--Return--"),
449 450 ("next", "----> 5 __debuggerskip__ = False"),
450 451 ]:
451 452 child.expect("ipdb>")
452 453 child.sendline(input_)
453 454 child.expect_exact(input_)
454 455 child.expect_exact(expected)
455 456
456 457 child.close()
457 458
458 459
459 460 @skip_win32
460 461 def test_decorator_skip_with_breakpoint():
461 462 """test that decorator frame skipping can be disabled"""
462 463
463 464 import pexpect
464 465
465 466 env = os.environ.copy()
466 467 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
467 468
468 469 child = pexpect.spawn(
469 470 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
470 471 )
471 472 child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
472 473
473 474 child.expect("IPython")
474 475 child.expect("\n")
475 476
476 477 ### we need a filename, so we need to exec the full block with a filename
477 478 with NamedTemporaryFile(suffix=".py", dir=".", delete=True) as tf:
478 479
479 480 name = tf.name[:-3].split("/")[-1]
480 481 tf.write("\n".join([dedent(x) for x in skip_decorators_blocks[:-1]]).encode())
481 482 tf.flush()
482 483 codeblock = f"from {name} import f"
483 484
484 485 dedented_blocks = [
485 486 codeblock,
486 487 "f()",
487 488 ]
488 489
489 490 in_prompt_number = 1
490 491 for cblock in dedented_blocks:
491 492 child.expect_exact(f"In [{in_prompt_number}]:")
492 493 in_prompt_number += 1
493 494 for line in cblock.splitlines():
494 495 child.sendline(line)
495 496 child.expect_exact(line)
496 497 child.sendline("")
497 498
498 499 # as the filename does not exists, we'll rely on the filename prompt
499 500 child.expect_exact("47 bar(3, 4)")
500 501
501 502 for input_, expected in [
502 503 (f"b {name}.py:3", ""),
503 504 ("step", "1---> 3 pass # should not stop here except"),
504 505 ("step", "---> 38 @pdb_skipped_decorator"),
505 506 ("continue", ""),
506 507 ]:
507 508 child.expect("ipdb>")
508 509 child.sendline(input_)
509 510 child.expect_exact(input_)
510 511 child.expect_exact(expected)
511 512
512 513 child.close()
513 514
514 515
515 516 @skip_win32
516 517 def test_where_erase_value():
517 518 """Test that `where` does not access f_locals and erase values."""
518 519 import pexpect
519 520
520 521 env = os.environ.copy()
521 522 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
522 523
523 524 child = pexpect.spawn(
524 525 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
525 526 )
526 527 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
527 528
528 529 child.expect("IPython")
529 530 child.expect("\n")
530 531 child.expect_exact("In [1]")
531 532
532 533 block = dedent(
533 534 """
534 535 def simple_f():
535 536 myvar = 1
536 537 print(myvar)
537 538 1/0
538 539 print(myvar)
539 540 simple_f() """
540 541 )
541 542
542 543 for line in block.splitlines():
543 544 child.sendline(line)
544 545 child.expect_exact(line)
545 546 child.expect_exact("ZeroDivisionError")
546 547 child.expect_exact("In [2]:")
547 548
548 549 child.sendline("%debug")
549 550
550 551 ##
551 552 child.expect("ipdb>")
552 553
553 554 child.sendline("myvar")
554 555 child.expect("1")
555 556
556 557 ##
557 558 child.expect("ipdb>")
558 559
559 560 child.sendline("myvar = 2")
560 561
561 562 ##
562 563 child.expect_exact("ipdb>")
563 564
564 565 child.sendline("myvar")
565 566
566 567 child.expect_exact("2")
567 568
568 569 ##
569 570 child.expect("ipdb>")
570 571 child.sendline("where")
571 572
572 573 ##
573 574 child.expect("ipdb>")
574 575 child.sendline("myvar")
575 576
576 577 child.expect_exact("2")
577 578 child.expect("ipdb>")
578 579
579 580 child.close()
@@ -1,1784 +1,1784 b''
1 1 ============
2 2 7.x Series
3 3 ============
4 4
5 5 .. _version 7.31.1:
6 6
7 7 IPython 7.31.1 (CVE-2022-21699)
8 8 ===============================
9 9
10 10 Fixed CVE-2022-21699, see IPython 8.0.1 release notes for informations.
11 11
12 12
13 13 .. _version 7.32:
14 14
15 15 IPython 7.32
16 16 ============
17 17
18 18
19 19
20 20 Autoload magic lazily
21 21 ---------------------
22 22
23 23 The ability to configure magics to be lazily loaded has been added to IPython.
24 24 See the ``ipython --help-all`` section on ``MagicsManager.lazy_magic``.
25 25 One can now use::
26 26
27 c.MagicsManger.lazy_magics = {
27 c.MagicsManager.lazy_magics = {
28 28 "my_magic": "slow.to.import",
29 29 "my_other_magic": "also.slow",
30 30 }
31 31
32 32 And on first use of ``%my_magic``, or corresponding cell magic, or other line magic,
33 33 the corresponding ``load_ext`` will be called just before trying to invoke the magic.
34 34
35 35 Misc
36 36 ----
37 37
38 38 - Update sphinxify for Docrepr 0.2.0 :ghpull:`13503`.
39 39 - Set co_name for cells run line by line (to fix debugging with Python 3.10)
40 40 :ghpull:`13535`
41 41
42 42
43 43 Many thanks to all the contributors to this release. You can find all individual
44 44 contributions to this milestone `on github
45 45 <https://github.com/ipython/ipython/milestone/99>`__.
46 46
47 47 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
48 48 work on IPython and related libraries.
49 49
50 50 .. _version 7.31:
51 51
52 52 IPython 7.31
53 53 ============
54 54
55 55 IPython 7.31 brings a couple of backports and fixes from the 8.0 branches,
56 56 it is likely one of the last releases of the 7.x series, as 8.0 will probably be released
57 57 between this release and what would have been 7.32.
58 58
59 59 Please test 8.0 beta/rc releases in addition to this release.
60 60
61 61 This Releases:
62 62 - Backport some fixes for Python 3.10 (:ghpull:`13412`)
63 63 - use full-alpha transparency on dvipng rendered LaTeX (:ghpull:`13372`)
64 64
65 65 Many thanks to all the contributors to this release. You can find all individual
66 66 contributions to this milestone `on github
67 67 <https://github.com/ipython/ipython/milestone/95>`__.
68 68
69 69 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
70 70 work on IPython and related libraries.
71 71
72 72
73 73 .. _version 7.30:
74 74
75 75 IPython 7.30
76 76 ============
77 77
78 78 IPython 7.30 fixes a couple of bugs introduce in previous releases (in
79 79 particular with respect to path handling), and introduce a few features and
80 80 improvements:
81 81
82 82 Notably we will highlight :ghpull:`13267` "Document that ``%run`` can execute
83 83 notebooks and ipy scripts.", which is the first commit of Fernando PΓ©rez since
84 84 mid 2016 (IPython 5.1). If you are new to IPython, Fernando created IPython in
85 85 2001. The other most recent contribution of Fernando to IPython itself was
86 86 May 2018, by reviewing and merging PRs. I want to note that Fernando is still
87 87 active but mostly as a mentor and leader of the whole Jupyter organisation, but
88 88 we're still happy to see him contribute code !
89 89
90 90 :ghpull:`13290` "Use sphinxify (if available) in object_inspect_mime path"
91 91 should allow richer Repr of docstrings when using jupyterlab inspector.
92 92
93 93 :ghpull:`13311` make the debugger use ``ThreadPoolExecutor`` for debugger cmdloop.
94 94 This should fix some issues/infinite loop, but let us know if you come across
95 95 any regressions. In particular this fixes issues with `kmaork/madbg <https://github.com/kmaork/madbg>`_,
96 96 a remote debugger for IPython.
97 97
98 98 Note that this is likely the ante-penultimate release of IPython 7.x as a stable
99 99 branch, as I hope to release IPython 8.0 as well as IPython 7.31 next
100 100 month/early 2022.
101 101
102 102 IPython 8.0 will drop support for Python 3.7, removed nose as a dependency, and
103 103 7.x will only get critical bug fixes with 8.x becoming the new stable. This will
104 104 not be possible without `NumFOCUS Small Development Grants
105 105 <https://numfocus.org/programs/small-development-grants>`_ Which allowed us to
106 106 hire `Nikita Kniazev <https://github.com/Kojoley>`_ who provide Python and C++
107 107 help and contracting work.
108 108
109 109
110 110 Many thanks to all the contributors to this release. You can find all individual
111 111 contributions to this milestone `on github
112 112 <https://github.com/ipython/ipython/milestone/94?closed=1>`__.
113 113
114 114 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
115 115 work on IPython and related libraries.
116 116
117 117
118 118 .. _version 7.29:
119 119
120 120 IPython 7.29
121 121 ============
122 122
123 123
124 124 IPython 7.29 brings a couple of new functionalities to IPython and a number of bugfixes.
125 125 It is one of the largest recent release, relatively speaking, with close to 15 Pull Requests.
126 126
127 127
128 128 - fix an issue where base64 was returned instead of bytes when showing figures :ghpull:`13162`
129 129 - fix compatibility with PyQt6, PySide 6 :ghpull:`13172`. This may be of
130 130 interest if you are running on Apple Silicon as only qt6.2+ is natively
131 131 compatible.
132 132 - fix matplotlib qtagg eventloop :ghpull:`13179`
133 133 - Multiple docs fixes, typos, ... etc.
134 134 - Debugger will now exit by default on SigInt :ghpull:`13218`, this will be
135 135 useful in notebook/lab if you forgot to exit the debugger. "Interrupt Kernel"
136 136 will now exist the debugger.
137 137
138 138 It give Pdb the ability to skip code in decorators. If functions contain a
139 139 special value names ``__debuggerskip__ = True|False``, the function will not be
140 140 stepped into, and Pdb will step into lower frames only if the value is set to
141 141 ``False``. The exact behavior is still likely to have corner cases and will be
142 142 refined in subsequent releases. Feedback welcome. See the debugger module
143 143 documentation for more info. Thanks to the `D. E. Shaw
144 144 group <https://deshaw.com/>`__ for funding this feature.
145 145
146 146 The main branch of IPython is receiving a number of changes as we received a
147 147 `NumFOCUS SDG <https://numfocus.org/programs/small-development-grants>`__
148 148 ($4800), to help us finish replacing ``nose`` by ``pytest``, and make IPython
149 149 future proof with an 8.0 release.
150 150
151 151
152 152 Many thanks to all the contributors to this release. You can find all individual
153 153 contributions to this milestone `on github
154 154 <https://github.com/ipython/ipython/milestone/93>`__.
155 155
156 156 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
157 157 work on IPython and related libraries.
158 158
159 159
160 160 .. _version 7.28:
161 161
162 162 IPython 7.28
163 163 ============
164 164
165 165
166 166 IPython 7.28 is again a minor release that mostly bring bugfixes, and couple of
167 167 improvement. Many thanks to MrMino, who again did all the work this month, and
168 168 made a number of documentation improvements.
169 169
170 170 Here is a non-exhaustive list of changes,
171 171
172 172 Fixes:
173 173
174 174 - async with doesn't allow newlines :ghpull:`13090`
175 175 - Dynamically changing to vi mode via %config magic) :ghpull:`13091`
176 176
177 177 Virtualenv handling fixes:
178 178
179 179 - init_virtualenv now uses Pathlib :ghpull:`12548`
180 180 - Fix Improper path comparison of virtualenv directories :ghpull:`13140`
181 181 - Fix virtual environment user warning for lower case pathes :ghpull:`13094`
182 182 - Adapt to all sorts of drive names for cygwin :ghpull:`13153`
183 183
184 184 New Features:
185 185
186 186 - enable autoplay in embed YouTube player :ghpull:`13133`
187 187
188 188 Documentation:
189 189
190 190 - Fix formatting for the core.interactiveshell documentation :ghpull:`13118`
191 191 - Fix broken ipyparallel's refs :ghpull:`13138`
192 192 - Improve formatting of %time documentation :ghpull:`13125`
193 193 - Reword the YouTubeVideo autoplay WN :ghpull:`13147`
194 194
195 195
196 196 Highlighted features
197 197 --------------------
198 198
199 199
200 200 ``YouTubeVideo`` autoplay and the ability to add extra attributes to ``IFrame``
201 201 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202 202
203 203 You can add any extra attributes to the ``<iframe>`` tag using the new
204 204 ``extras`` argument in the ``IFrame`` class. For example::
205 205
206 206 In [1]: from IPython.display import IFrame
207 207
208 208 In [2]: IFrame(src="src", width=300, height=300, extras=['loading="eager"'])
209 209
210 210 The above cells will result in the following HTML code being displayed in a
211 211 notebook::
212 212
213 213 <iframe
214 214 width="300"
215 215 height="300"
216 216 src="src"
217 217 frameborder="0"
218 218 allowfullscreen
219 219 loading="eager"
220 220 ></iframe>
221 221
222 222 Related to the above, the ``YouTubeVideo`` class now takes an
223 223 ``allow_autoplay`` flag, which sets up the iframe of the embedded YouTube video
224 224 such that it allows autoplay.
225 225
226 226 .. note::
227 227 Whether this works depends on the autoplay policy of the browser rendering
228 228 the HTML allowing it. It also could get blocked by some browser extensions.
229 229
230 230 Try it out!
231 231 ::
232 232
233 233 In [1]: from IPython.display import YouTubeVideo
234 234
235 235 In [2]: YouTubeVideo("dQw4w9WgXcQ", allow_autoplay=True)
236 236
237 237
238 238
239 239 Thanks
240 240 ------
241 241
242 242 Many thanks to all the contributors to this release. You can find all individual
243 243 contributions to this milestone `on github
244 244 <https://github.com/ipython/ipython/milestone/92>`__.
245 245
246 246 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
247 247 work on IPython and related libraries.
248 248
249 249
250 250 .. _version 7.27:
251 251
252 252 IPython 7.27
253 253 ============
254 254
255 255 IPython 7.27 is a minor release that fixes a couple of issues and compatibility.
256 256
257 257 - Add support for GTK4 :ghpull:`131011`
258 258 - Add support for Qt6 :ghpull:`13085`
259 259 - Fix an issue with pip magic on windows :ghpull:`13093`
260 260
261 261 Thanks
262 262 ------
263 263
264 264 Many thanks to all the contributors to this release. You can find all individual
265 265 contributions to this milestone `on github
266 266 <https://github.com/ipython/ipython/milestone/91>`__.
267 267
268 268 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
269 269 work on IPython and related libraries.
270 270
271 271 .. _version 7.26:
272 272
273 273 IPython 7.26
274 274 ============
275 275
276 276 IPython 7.26 is a minor release that fixes a couple of issues, updates in API
277 277 and Copyright/Licenses issues around various part of the codebase.
278 278
279 279 We'll highlight `this issue <https://github.com/ipython/ipython/issues/13039>`
280 280 pointing out we were including and refereeing to code from Stack Overflow which
281 281 was CC-BY-SA, hence incompatible with the BSD license of IPython. This lead us
282 282 to a rewriting of the corresponding logic which in our case was done in a more
283 283 efficient way (in our case we were searching string prefixes instead of full
284 284 strings).
285 285
286 286 You will notice also a number of documentation improvements and cleanup.
287 287
288 288 Of particular interest are the following Pull-requests:
289 289
290 290
291 291 - The IPython directive now uses Sphinx logging for warnings. :ghpull:`13030`.
292 292 - Add expiry days option to pastebin magic and change http protocol to https.
293 293 :ghpull:`13056`
294 294 - Make Ipython.utils.timing work with jupyterlite :ghpull:`13050`.
295 295
296 296 Pastebin magic expiry days option
297 297 ---------------------------------
298 298
299 299 The Pastebin magic now has ``-e`` option to determine
300 300 the number of days for paste expiration. For example
301 301 the paste that created with ``%pastebin -e 20 1`` magic will
302 302 be available for next 20 days.
303 303
304 304
305 305
306 306
307 307
308 308 Thanks
309 309 ------
310 310
311 311 Many thanks to all the contributors to this release and in particular MrMino who
312 312 is doing most of the work those days. You can find all individual contributions
313 313 to this milestone `on github <https://github.com/ipython/ipython/milestone/90>`__.
314 314
315 315 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
316 316 work on IPython and related libraries.
317 317
318 318
319 319 .. _version 7.25:
320 320
321 321 IPython 7.25
322 322 ============
323 323
324 324 IPython 7.25 is a minor release that contains a single bugfix, which is highly
325 325 recommended for all users of ipdb, ipython debugger %debug magic and similar.
326 326
327 327 Issuing commands like ``where`` from within the debugger would reset the
328 328 local variables changes made by the user. It is interesting to look at the root
329 329 cause of the issue as accessing an attribute (``frame.f_locals``) would trigger
330 330 this side effects.
331 331
332 332 Thanks in particular to the patience from the reporters at D.E. Shaw for their
333 333 initial bug report that was due to a similar coding oversight in an extension,
334 334 and who took time to debug and narrow down the problem.
335 335
336 336 Thanks
337 337 ------
338 338
339 339 Many thanks to all the contributors to this release you can find all individual
340 340 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/89>`__.
341 341
342 342 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
343 343 work on IPython and related libraries.
344 344
345 345
346 346 .. _version 7.24:
347 347
348 348 IPython 7.24
349 349 ============
350 350
351 351 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
352 352 typical updates:
353 353
354 354 Misc
355 355 ----
356 356
357 357
358 358 - Fix an issue where ``%recall`` would both succeeded and print an error message
359 359 it failed. :ghpull:`12952`
360 360 - Drop support for NumPy 1.16 – practically has no effect beyond indicating in
361 361 package metadata that we do not support it. :ghpull:`12937`
362 362
363 363 Debugger improvements
364 364 ---------------------
365 365
366 366 The debugger (and ``%debug`` magic) have been improved and can skip or hide frames
367 367 originating from files that are not writable to the user, as these are less
368 368 likely to be the source of errors, or be part of system files this can be a useful
369 369 addition when debugging long errors.
370 370
371 371 In addition to the global ``skip_hidden True|False`` command, the debugger has
372 372 gained finer grained control of predicates as to whether to a frame should be
373 373 considered hidden. So far 3 predicates are available :
374 374
375 375 - ``tbhide``: frames containing the local variable ``__tracebackhide__`` set to
376 376 True.
377 377 - ``readonly``: frames originating from readonly files, set to False.
378 378 - ``ipython_internal``: frames that are likely to be from IPython internal
379 379 code, set to True.
380 380
381 381 You can toggle individual predicates during a session with
382 382
383 383 .. code-block::
384 384
385 385 ipdb> skip_predicates readonly True
386 386
387 387 Read-only files will now be considered hidden frames.
388 388
389 389
390 390 You can call ``skip_predicates`` without arguments to see the states of current
391 391 predicates:
392 392
393 393 .. code-block::
394 394
395 395 ipdb> skip_predicates
396 396 current predicates:
397 397 tbhide : True
398 398 readonly : False
399 399 ipython_internal : True
400 400
401 401 If all predicates are set to ``False``, ``skip_hidden`` will practically have
402 402 no effect. We attempt to warn you when all predicates are False.
403 403
404 404 Note that the ``readonly`` predicate may increase disk access as we check for
405 405 file access permission for all frames on many command invocation, but is usually
406 406 cached by operating systems. Let us know if you encounter any issues.
407 407
408 408 As the IPython debugger does not use the traitlets infrastructure for
409 409 configuration, by editing your ``.pdbrc`` files and appending commands you would
410 410 like to be executed just before entering the interactive prompt. For example:
411 411
412 412
413 413 .. code::
414 414
415 415 # file : ~/.pdbrc
416 416 skip_predicates readonly True
417 417 skip_predicates tbhide False
418 418
419 419 Will hide read only frames by default and show frames marked with
420 420 ``__tracebackhide__``.
421 421
422 422
423 423
424 424
425 425 Thanks
426 426 ------
427 427
428 428 Many thanks to all the contributors to this release you can find all individual
429 429 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/87>`__.
430 430
431 431 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
432 432 work on IPython and related libraries, in particular above mentioned
433 433 improvements to the debugger.
434 434
435 435
436 436
437 437
438 438 .. _version 7.23:
439 439
440 440 IPython 7.23 and 7.23.1
441 441 =======================
442 442
443 443
444 444 Third release of IPython for 2021, mostly containing bug fixes. A couple of not
445 445 typical updates:
446 446
447 447 - We moved to GitHub actions away from Travis-CI, the transition may not be
448 448 100% complete (not testing on nightly anymore), but as we ran out of
449 449 Travis-Ci hours on the IPython organisation that was a necessary step.
450 450 :ghpull:`12900`.
451 451
452 452 - We have a new dependency: ``matplotlib-inline``, which try to extract
453 453 matplotlib inline backend specific behavior. It is available on PyPI and
454 454 conda-forge thus should not be a problem to upgrade to this version. If you
455 455 are a package maintainer that might be an extra dependency to package first.
456 456 :ghpull:`12817` (IPython 7.23.1 fix a typo that made this change fail)
457 457
458 458 In the addition/new feature category, ``display()`` now have a ``clear=True``
459 459 option to clear the display if any further outputs arrives, allowing users to
460 460 avoid having to use ``clear_output()`` directly. :ghpull:`12823`.
461 461
462 462 In bug fixes category, this release fix an issue when printing tracebacks
463 463 containing Unicode characters :ghpull:`12758`.
464 464
465 465 In code cleanup category :ghpull:`12932` remove usage of some deprecated
466 466 functionality for compatibility with Python 3.10.
467 467
468 468
469 469
470 470 Thanks
471 471 ------
472 472
473 473 Many thanks to all the contributors to this release you can find all individual
474 474 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/86>`__.
475 475 In particular MrMino for responding to almost all new issues, and triaging many
476 476 of the old ones, as well as takluyver, minrk, willingc for reacting quikly when
477 477 we ran out of CI Hours.
478 478
479 479 Thanks as well to organisations, QuantStack (martinRenou and SylvainCorlay) for
480 480 extracting matplotlib inline backend into its own package, and the `D. E. Shaw group
481 481 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
482 482
483 483
484 484 .. _version 7.22:
485 485
486 486 IPython 7.22
487 487 ============
488 488
489 489 Second release of IPython for 2021, mostly containing bug fixes. Here is a quick
490 490 rundown of the few changes.
491 491
492 492 - Fix some ``sys.excepthook`` shenanigan when embedding with qt, recommended if
493 493 you – for example – use `napari <https://napari.org>`__. :ghpull:`12842`.
494 494 - Fix bug when using the new ipdb ``%context`` magic :ghpull:`12844`
495 495 - Couples of deprecation cleanup :ghpull:`12868`
496 496 - Update for new dpast.com api if you use the ``%pastbin`` magic. :ghpull:`12712`
497 497 - Remove support for numpy before 1.16. :ghpull:`12836`
498 498
499 499
500 500 Thanks
501 501 ------
502 502
503 503 We have a new team member that you should see more often on the IPython
504 504 repository, BΕ‚aΕΌej Michalik (@MrMino) have been doing regular contributions to
505 505 IPython, and spent time replying to many issues and guiding new users to the
506 506 codebase; they now have triage permissions to the IPython repository and we'll
507 507 work toward giving them more permission in the future.
508 508
509 509 Many thanks to all the contributors to this release you can find all individual
510 510 contributions to this milestone `on github <https://github.com/ipython/ipython/milestone/84>`__.
511 511
512 512 Thanks as well to organisations, QuantStack for working on debugger
513 513 compatibility for Xeus_python, and the `D. E. Shaw group
514 514 <https://deshaw.com/>`__ for sponsoring work on IPython and related libraries.
515 515
516 516 .. _version 721:
517 517
518 518 IPython 7.21
519 519 ============
520 520
521 521 IPython 7.21 is the first release we have back on schedule of one release every
522 522 month; it contains a number of minor fixes and improvements, notably, the new
523 523 context command for ipdb
524 524
525 525
526 526 New "context" command in ipdb
527 527 -----------------------------
528 528
529 529 It is now possible to change the number of lines shown in the backtrace
530 530 information in ipdb using "context" command. :ghpull:`12826`
531 531
532 532 (thanks @MrMino, there are other improvement from them on master).
533 533
534 534 Other notable changes in IPython 7.21
535 535 -------------------------------------
536 536
537 537 - Fix some issues on new osx-arm64 :ghpull:`12804`, :ghpull:`12807`.
538 538 - Compatibility with Xeus-Python for debugger protocol, :ghpull:`12809`
539 539 - Misc docs fixes for compatibility and uniformity with Numpydoc.
540 540 :ghpull:`12824`
541 541
542 542
543 543 Thanks
544 544 ------
545 545
546 546 Many thanks to all the contributors to this release you can find all individual
547 547 contribution to this milestone `on github <https://github.com/ipython/ipython/milestone/83>`__.
548 548
549 549
550 550 .. _version 720:
551 551
552 552 IPython 7.20
553 553 ============
554 554
555 555 IPython 7.20 is the accumulation of 3 month of work on IPython, spacing between
556 556 IPython release have been increased from the usual once a month for various
557 557 reason.
558 558
559 559 - Mainly as I'm too busy and the effectively sole maintainer, and
560 560 - Second because not much changes happened before mid December.
561 561
562 562 The main driver for this release was the new version of Jedi 0.18 breaking API;
563 563 which was taken care of in the master branch early in 2020 but not in 7.x as I
564 564 though that by now 8.0 would be out.
565 565
566 566 The inclusion of a resolver in pip did not help and actually made things worse.
567 567 If usually I would have simply pinned Jedi to ``<0.18``; this is not a solution
568 568 anymore as now pip is free to install Jedi 0.18, and downgrade IPython.
569 569
570 570 I'll do my best to keep the regular release, but as the 8.0-dev branch and 7.x
571 571 are starting to diverge this is becoming difficult in particular with my limited
572 572 time, so if you have any cycles to spare I'll appreciate your help to respond to
573 573 issues and pushing 8.0 forward.
574 574
575 575 Here are thus some of the changes for IPython 7.20.
576 576
577 577 - Support for PyQt5 >= 5.11 :ghpull:`12715`
578 578 - ``%reset`` remove imports more agressively :ghpull:`12718`
579 579 - fix the ``%conda`` magic :ghpull:`12739`
580 580 - compatibility with Jedi 0.18, and bump minimum Jedi version. :ghpull:`12793`
581 581
582 582
583 583 .. _version 719:
584 584
585 585 IPython 7.19
586 586 ============
587 587
588 588 IPython 7.19 accumulative two month of works, bug fixes and improvements, there
589 589 was exceptionally no release last month.
590 590
591 591 - Fix to restore the ability to specify more than one extension using command
592 592 line flags when using traitlets 5.0 :ghpull:`12543`
593 593 - Docs docs formatting that make the install commands work on zsh
594 594 :ghpull:`12587`
595 595 - Always display the last frame in tracebacks even if hidden with
596 596 ``__tracebackhide__`` :ghpull:`12601`
597 597 - Avoid an issue where a callback can be registered multiple times.
598 598 :ghpull:`12625`
599 599 - Avoid an issue in debugger mode where frames changes could be lost.
600 600 :ghpull:`12627`
601 601
602 602 - Never hide the frames that invoke a debugger, even if marked as hidden by
603 603 ``__tracebackhide__`` :ghpull:`12631`
604 604 - Fix calling the debugger in a recursive manner :ghpull:`12659`
605 605
606 606
607 607 A number of code changes have landed on master and we are getting close to
608 608 enough new features and codebase improvement that a 8.0 start to make sens.
609 609 For downstream packages, please start working on migrating downstream testing
610 610 away from iptest and using pytest, as nose will not work on Python 3.10 and we
611 611 will likely start removing it as a dependency for testing.
612 612
613 613 .. _version 718:
614 614
615 615 IPython 7.18
616 616 ============
617 617
618 618 IPython 7.18 is a minor release that mostly contains bugfixes.
619 619
620 620 - ``CRLF`` is now handled by magics my default; solving some issues due to copy
621 621 pasting on windows. :ghpull:`12475`
622 622
623 623 - Requiring pexpect ``>=4.3`` as we are Python 3.7+ only and earlier version of
624 624 pexpect will be incompatible. :ghpull:`12510`
625 625
626 626 - Minimum jedi version is now 0.16. :ghpull:`12488`
627 627
628 628
629 629
630 630 .. _version 717:
631 631
632 632 IPython 7.17
633 633 ============
634 634
635 635 IPython 7.17 brings a couple of new improvements to API and a couple of user
636 636 facing changes to make the terminal experience more user friendly.
637 637
638 638 :ghpull:`12407` introduces the ability to pass extra argument to the IPython
639 639 debugger class; this is to help a new project from ``kmaork``
640 640 (https://github.com/kmaork/madbg) to feature a fully remote debugger.
641 641
642 642 :ghpull:`12410` finally remove support for 3.6, while the codebase is still
643 643 technically compatible; IPython will not install on Python 3.6.
644 644
645 645 lots of work on the debugger and hidden frames from ``@impact27`` in
646 646 :ghpull:`12437`, :ghpull:`12445`, :ghpull:`12460` and in particular
647 647 :ghpull:`12453` which make the debug magic more robust at handling spaces.
648 648
649 649 Biggest API addition is code transformation which is done before code execution;
650 650 IPython allows a number of hooks to catch non-valid Python syntax (magic, prompt
651 651 stripping...etc). Transformers are usually called many time; typically:
652 652
653 653 - When trying to figure out whether the code is complete and valid (should we
654 654 insert a new line or execute ?)
655 655 - During actual code execution pass before giving the code to Python's
656 656 ``exec``.
657 657
658 658 This lead to issues when transformer might have had side effects; or do external
659 659 queries. Starting with IPython 7.17 you can expect your transformer to be called
660 660 less time.
661 661
662 662 Input transformers are now called only once in the execution path of
663 663 `InteractiveShell`, allowing to register transformer that potentially have side
664 664 effects (note that this is not recommended). Internal methods `should_run_async`, and
665 665 `run_cell_async` now take a recommended optional `transformed_cell`, and
666 666 `preprocessing_exc_tuple` parameters that will become mandatory at some point in
667 667 the future; that is to say cells need to be explicitly transformed to be valid
668 668 Python syntax ahead of trying to run them. :ghpull:`12440`;
669 669
670 670 ``input_transformers`` can now also have an attribute ``has_side_effects`` set
671 671 to `True`, when this attribute is present; this will prevent the transformers
672 672 from being ran when IPython is trying to guess whether the user input is
673 673 complete. Note that this may means you will need to explicitly execute in some
674 674 case where your transformations are now not ran; but will not affect users with
675 675 no custom extensions.
676 676
677 677
678 678 API Changes
679 679 -----------
680 680
681 681 Change of API and exposed objects automatically detected using `frappuccino
682 682 <https://pypi.org/project/frappuccino/>`_
683 683
684 684
685 685 The following items are new since 7.16.0::
686 686
687 687 + IPython.core.interactiveshell.InteractiveShell.get_local_scope(self, stack_depth)
688 688
689 689 The following signatures differ since 7.16.0::
690 690
691 691 - IPython.core.interactiveshell.InteractiveShell.run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True)
692 692 + 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)
693 693
694 694 - IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell)
695 695 + IPython.core.interactiveshell.InteractiveShell.should_run_async(self, raw_cell, *, transformed_cell=None, preprocessing_exc_tuple=None)
696 696
697 697 - IPython.terminal.debugger.TerminalPdb.pt_init(self)
698 698 + IPython.terminal.debugger.TerminalPdb.pt_init(self, pt_session_options=None)
699 699
700 700 This method was added::
701 701
702 702 + IPython.core.interactiveshell.InteractiveShell.get_local_scope
703 703
704 704 Which is now also present on subclasses::
705 705
706 706 + IPython.terminal.embed.InteractiveShellEmbed.get_local_scope
707 707 + IPython.terminal.interactiveshell.TerminalInteractiveShell.get_local_scope
708 708
709 709
710 710 .. _version 716:
711 711
712 712 IPython 7.16.1, 7.16.2
713 713 ======================
714 714
715 715 IPython 7.16.1 was release immediately after 7.16.0 to fix a conda packaging issue.
716 716 The source is identical to 7.16.0 but the file permissions in the tar are different.
717 717
718 718 IPython 7.16.2 pins jedi dependency to "<=0.17.2" which should prevent some
719 719 issues for users still on python 3.6. This may not be sufficient as pip may
720 720 still allow to downgrade IPython.
721 721
722 722 Compatibility with Jedi > 0.17.2 was not added as this would have meant bumping
723 723 the minimal version to >0.16.
724 724
725 725 IPython 7.16
726 726 ============
727 727
728 728
729 729 The default traceback mode will now skip frames that are marked with
730 730 ``__tracebackhide__ = True`` and show how many traceback frames have been
731 731 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
732 732 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
733 733
734 734 The ipython debugger also now understands ``__tracebackhide__`` as well and will
735 735 skip hidden frames when displaying. Movement up and down the stack will skip the
736 736 hidden frames and will show how many frames were hidden. Internal IPython frames
737 737 are also now hidden by default. The behavior can be changed with the
738 738 ``skip_hidden`` while in the debugger, command and accepts "yes", "no", "true"
739 739 and "false" case insensitive parameters.
740 740
741 741
742 742 Misc Noticeable changes:
743 743 ------------------------
744 744
745 745 - Exceptions are now (re)raised when running notebooks via the :magic:`%run`, helping to catch issues in workflows and
746 746 pipelines. :ghpull:`12301`
747 747 - Fix inputhook for qt 5.15.0 :ghpull:`12355`
748 748 - Fix wx inputhook :ghpull:`12375`
749 749 - Add handling for malformed pathext env var (Windows) :ghpull:`12367`
750 750 - use $SHELL in system_piped :ghpull:`12360` for uniform behavior with
751 751 ipykernel.
752 752
753 753 Reproducible Build
754 754 ------------------
755 755
756 756 IPython 7.15 reproducible build did not work, so we try again this month
757 757 :ghpull:`12358`.
758 758
759 759
760 760 API Changes
761 761 -----------
762 762
763 763 Change of API and exposed objects automatically detected using `frappuccino
764 764 <https://pypi.org/project/frappuccino/>`_ (still in beta):
765 765
766 766
767 767 The following items are new and mostly related to understanding ``__tracebackhide__``::
768 768
769 769 + IPython.core.debugger.Pdb.do_down(self, arg)
770 770 + IPython.core.debugger.Pdb.do_skip_hidden(self, arg)
771 771 + IPython.core.debugger.Pdb.do_up(self, arg)
772 772 + IPython.core.debugger.Pdb.hidden_frames(self, stack)
773 773 + IPython.core.debugger.Pdb.stop_here(self, frame)
774 774
775 775
776 776 The following items have been removed::
777 777
778 778 - IPython.core.debugger.Pdb.new_do_down
779 779 - IPython.core.debugger.Pdb.new_do_up
780 780
781 781 Those were implementation details.
782 782
783 783
784 784 .. _version 715:
785 785
786 786 IPython 7.15
787 787 ============
788 788
789 789 IPython 7.15 brings a number of bug fixes and user facing improvements.
790 790
791 791 Misc Noticeable changes:
792 792 ------------------------
793 793
794 794 - Long completion name have better elision in terminal :ghpull:`12284`
795 795 - I've started to test on Python 3.9 :ghpull:`12307` and fix some errors.
796 796 - Hi DPI scaling of figures when using qt eventloop :ghpull:`12314`
797 797 - Document the ability to have systemwide configuration for IPython.
798 798 :ghpull:`12328`
799 799 - Fix issues with input autoformatting :ghpull:`12336`
800 800 - ``IPython.core.debugger.Pdb`` is now interruptible (:ghpull:`12168`, in 7.14
801 801 but forgotten in release notes)
802 802 - Video HTML attributes (:ghpull:`12212`, in 7.14 but forgotten in release
803 803 notes)
804 804
805 805 Reproducible Build
806 806 ------------------
807 807
808 808 Starting with IPython 7.15, I am attempting to provide reproducible builds,
809 809 that is to say you should be able from the source tree to generate an sdist
810 810 and wheel that are identical byte for byte with the publish version on PyPI.
811 811
812 812 I've only tested on a couple of machines so far and the process is relatively
813 813 straightforward, so this mean that IPython not only have a deterministic build
814 814 process, but also I have either removed, or put under control all effects of
815 815 the build environments on the final artifact. I encourage you to attempt the
816 816 build process on your machine as documented in :ref:`core_developer_guide`
817 817 and let me know if you do not obtain an identical artifact.
818 818
819 819 While reproducible builds is critical to check that the supply chain of (open
820 820 source) software has not been compromised, it can also help to speedup many
821 821 of the build processes in large environment (conda, apt...) by allowing
822 822 better caching of intermediate build steps.
823 823
824 824 Learn more on `<https://reproducible-builds.org/>`_. `Reflections on trusting
825 825 trust <https://dl.acm.org/doi/10.1145/358198.358210>`_ is also one of the
826 826 cornerstone and recommended reads on this subject.
827 827
828 828 .. note::
829 829
830 830 The build commit from which the sdist is generated is also `signed
831 831 <https://en.wikipedia.org/wiki/Digital_signature>`_, so you should be able to
832 832 check it has not been compromised, and the git repository is a `merkle-tree
833 833 <https://en.wikipedia.org/wiki/Merkle_tree>`_, you can check the consistency
834 834 with `git-fsck <https://git-scm.com/docs/git-fsck>`_ which you likely `want
835 835 to enable by default
836 836 <https://gist.github.com/mbbx6spp/14b86437e794bffb4120>`_.
837 837
838 838 NEP29: Last version to support Python 3.6
839 839 -----------------------------------------
840 840
841 841 IPython 7.15 will be the Last IPython version to officially support Python
842 842 3.6, as stated by `NumPy Enhancement Proposal 29
843 843 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_. Starting with
844 844 next minor version of IPython I may stop testing on Python 3.6 and may stop
845 845 publishing release artifacts that install on Python 3.6
846 846
847 847 Highlighted features
848 848 --------------------
849 849
850 850 Highlighted features are not new, but seem to not be widely known, this
851 851 section will help you discover in more narrative form what you can do with
852 852 IPython.
853 853
854 854 Increase Tab Completion Menu Height
855 855 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
856 856
857 857 In terminal IPython it is possible to increase the hight of the tab-completion
858 858 menu. To do so set the value of
859 859 :configtrait:`TerminalInteractiveShell.space_for_menu`, this will reserve more
860 860 space at the bottom of the screen for various kind of menus in IPython including
861 861 tab completion and searching in history.
862 862
863 863 Autoformat Code in the terminal
864 864 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
865 865
866 866 If you have a preferred code formatter, you can configure IPython to
867 867 reformat your code. Set the value of
868 868 :configtrait:`TerminalInteractiveShell.autoformatter` to for example ``'black'``
869 869 and IPython will auto format your code when possible.
870 870
871 871
872 872 .. _version 714:
873 873
874 874 IPython 7.14
875 875 ============
876 876
877 877 IPython 7.14 is a minor release that fix a couple of bugs and prepare
878 878 compatibility with new or future versions of some libraries.
879 879
880 880 Important changes:
881 881 ------------------
882 882
883 883 - Fix compatibility with Sphinx 3+ :ghpull:`12235`
884 884 - Remove deprecated matplotlib parameter usage, compatibility with matplotlib
885 885 3.3+ :`122250`
886 886
887 887 Misc Changes
888 888 ------------
889 889
890 890 - set ``.py`` extension when editing current buffer in vi/emacs. :ghpull:`12167`
891 891 - support for unicode identifiers in ``?``/``??`` :ghpull:`12208`
892 892 - add extra options to the ``Video`` Rich objects :ghpull:`12212`
893 893 - add pretty-printing to ``SimpleNamespace`` :ghpull:`12230`
894 894
895 895 IPython.core.debugger.Pdb is now interruptible
896 896 ----------------------------------------------
897 897
898 898 A ``KeyboardInterrupt`` will now interrupt IPython's extended debugger, in order to make Jupyter able to interrupt it. (:ghpull:`12168`)
899 899
900 900 Video HTML attributes
901 901 ---------------------
902 902
903 903 Add an option to `IPython.display.Video` to change the attributes of the HTML display of the video (:ghpull:`12212`)
904 904
905 905
906 906 Pending deprecated imports
907 907 --------------------------
908 908
909 909 Many object present in ``IPython.core.display`` are there for internal use only,
910 910 and should already been imported from ``IPython.display`` by users and external
911 911 libraries. Trying to import those from ``IPython.core.display`` is still possible
912 912 but will trigger a
913 913 deprecation warning in later versions of IPython and will become errors in the
914 914 future.
915 915
916 916 This will simplify compatibility with other Python kernels (like Xeus-Python),
917 917 and simplify code base.
918 918
919 919
920 920
921 921
922 922 .. _version 713:
923 923
924 924 IPython 7.13
925 925 ============
926 926
927 927 IPython 7.13 is the final release of the 7.x branch since master is diverging
928 928 toward an 8.0. Exiting new features have already been merged in 8.0 and will
929 929 not be available on the 7.x branch. All the changes below have been backported
930 930 from the master branch.
931 931
932 932
933 933 - Fix inability to run PDB when inside an event loop :ghpull:`12141`
934 934 - Fix ability to interrupt some processes on windows :ghpull:`12137`
935 935 - Fix debugger shortcuts :ghpull:`12132`
936 936 - improve tab completion when inside a string by removing irrelevant elements :ghpull:`12128`
937 937 - Fix display of filename tab completion when the path is long :ghpull:`12122`
938 938 - Many removal of Python 2 specific code path :ghpull:`12110`
939 939 - displaying wav files do not require NumPy anymore, and is 5x to 30x faster :ghpull:`12113`
940 940
941 941 See the list of all closed issues and pull request on `github
942 942 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A7.13>`_.
943 943
944 944 .. _version 712:
945 945
946 946 IPython 7.12
947 947 ============
948 948
949 949 IPython 7.12 is a minor update that mostly brings code cleanup, removal of
950 950 longtime deprecated function and a couple update to documentation cleanup as well.
951 951
952 952 Notable changes are the following:
953 953
954 954 - Exit non-zero when ipython is given a file path to run that doesn't exist :ghpull:`12074`
955 955 - Test PR on ARM64 with Travis-CI :ghpull:`12073`
956 956 - Update CI to work with latest Pytest :ghpull:`12086`
957 957 - Add infrastructure to run ipykernel eventloop via trio :ghpull:`12097`
958 958 - Support git blame ignore revs :ghpull:`12091`
959 959 - Start multi-line ``__repr__`` s on their own line :ghpull:`12099`
960 960
961 961 .. _version 7111:
962 962
963 963 IPython 7.11.1
964 964 ==============
965 965
966 966 A couple of deprecated functions (no-op) have been reintroduces in py3compat as
967 967 Cython was still relying on them, and will be removed in a couple of versions.
968 968
969 969 .. _version 711:
970 970
971 971 IPython 7.11
972 972 ============
973 973
974 974 IPython 7.11 received a couple of compatibility fixes and code cleanup.
975 975
976 976 A number of function in the ``py3compat`` have been removed; a number of types
977 977 in the IPython code base are now non-ambiguous and now always ``unicode``
978 978 instead of ``Union[Unicode,bytes]``; many of the relevant code path have thus
979 979 been simplified/cleaned and types annotation added.
980 980
981 981 IPython support several verbosity level from exceptions. ``xmode plain`` now
982 982 support chained exceptions. :ghpull:`11999`
983 983
984 984 We are starting to remove ``shell=True`` in some usages of subprocess. While not directly
985 985 a security issue (as IPython is made to run arbitrary code anyway) it is not good
986 986 practice and we'd like to show the example. :ghissue:`12023`. This discussion
987 987 was started by ``@mschwager`` thanks to a new auditing tool they are working on
988 988 with duo-labs (`dlint <https://github.com/duo-labs/dlint>`_).
989 989
990 990 Work around some bugs in Python 3.9 tokenizer :ghpull:`12057`
991 991
992 992 IPython will now print its version after a crash. :ghpull:`11986`
993 993
994 994 This is likely the last release from the 7.x series that will see new feature.
995 995 The master branch will soon accept large code changes and thrilling new
996 996 features; the 7.x branch will only start to accept critical bug fixes, and
997 997 update dependencies.
998 998
999 999 .. _version 7102:
1000 1000
1001 1001 IPython 7.10.2
1002 1002 ==============
1003 1003
1004 1004 IPython 7.10.2 fix a couple of extra incompatibility between IPython, ipdb,
1005 1005 asyncio and Prompt Toolkit 3.
1006 1006
1007 1007 .. _version 7101:
1008 1008
1009 1009 IPython 7.10.1
1010 1010 ==============
1011 1011
1012 1012 IPython 7.10.1 fix a couple of incompatibilities with Prompt toolkit 3 (please
1013 1013 update Prompt toolkit to 3.0.2 at least), and fixes some interaction with
1014 1014 headless IPython.
1015 1015
1016 1016 .. _version 7100:
1017 1017
1018 1018 IPython 7.10.0
1019 1019 ==============
1020 1020
1021 1021 IPython 7.10 is the first double digit minor release in the last decade, and
1022 1022 first since the release of IPython 1.0, previous double digit minor release was
1023 1023 in August 2009.
1024 1024
1025 1025 We've been trying to give you regular release on the last Friday of every month
1026 1026 for a guaranty of rapid access to bug fixes and new features.
1027 1027
1028 1028 Unlike the previous first few releases that have seen only a couple of code
1029 1029 changes, 7.10 bring a number of changes, new features and bugfixes.
1030 1030
1031 1031 Stop Support for Python 3.5 – Adopt NEP 29
1032 1032 ------------------------------------------
1033 1033
1034 1034 IPython has decided to follow the informational `NEP 29
1035 1035 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`_ which layout a clear
1036 1036 policy as to which version of (C)Python and NumPy are supported.
1037 1037
1038 1038 We thus dropped support for Python 3.5, and cleaned up a number of code path
1039 1039 that were Python-version dependant. If you are on 3.5 or earlier pip should
1040 1040 automatically give you the latest compatible version of IPython so you do not
1041 1041 need to pin to a given version.
1042 1042
1043 1043 Support for Prompt Toolkit 3.0
1044 1044 ------------------------------
1045 1045
1046 1046 Prompt Toolkit 3.0 was release a week before IPython 7.10 and introduces a few
1047 1047 breaking changes. We believe IPython 7.10 should be compatible with both Prompt
1048 1048 Toolkit 2.x and 3.x, though it has not been extensively tested with 3.x so
1049 1049 please report any issues.
1050 1050
1051 1051
1052 1052 Prompt Rendering Performance improvements
1053 1053 -----------------------------------------
1054 1054
1055 1055 Pull Request :ghpull:`11933` introduced an optimisation in the prompt rendering
1056 1056 logic that should decrease the resource usage of IPython when using the
1057 1057 _default_ configuration but could potentially introduce a regression of
1058 1058 functionalities if you are using a custom prompt.
1059 1059
1060 1060 We know assume if you haven't changed the default keybindings that the prompt
1061 1061 **will not change** during the duration of your input – which is for example
1062 1062 not true when using vi insert mode that switches between `[ins]` and `[nor]`
1063 1063 for the current mode.
1064 1064
1065 1065 If you are experiencing any issue let us know.
1066 1066
1067 1067 Code autoformatting
1068 1068 -------------------
1069 1069
1070 1070 The IPython terminal can now auto format your code just before entering a new
1071 1071 line or executing a command. To do so use the
1072 1072 ``--TerminalInteractiveShell.autoformatter`` option and set it to ``'black'``;
1073 1073 if black is installed IPython will use black to format your code when possible.
1074 1074
1075 1075 IPython cannot always properly format your code; in particular it will
1076 1076 auto formatting with *black* will only work if:
1077 1077
1078 1078 - Your code does not contains magics or special python syntax.
1079 1079
1080 1080 - There is no code after your cursor.
1081 1081
1082 1082 The Black API is also still in motion; so this may not work with all versions of
1083 1083 black.
1084 1084
1085 1085 It should be possible to register custom formatter, though the API is till in
1086 1086 flux.
1087 1087
1088 1088 Arbitrary Mimetypes Handing in Terminal (Aka inline images in terminal)
1089 1089 -----------------------------------------------------------------------
1090 1090
1091 1091 When using IPython terminal it is now possible to register function to handle
1092 1092 arbitrary mimetypes. While rendering non-text based representation was possible in
1093 1093 many jupyter frontend; it was not possible in terminal IPython, as usually
1094 1094 terminal are limited to displaying text. As many terminal these days provide
1095 1095 escape sequences to display non-text; bringing this loved feature to IPython CLI
1096 1096 made a lot of sens. This functionality will not only allow inline images; but
1097 1097 allow opening of external program; for example ``mplayer`` to "display" sound
1098 1098 files.
1099 1099
1100 1100 So far only the hooks necessary for this are in place, but no default mime
1101 1101 renderers added; so inline images will only be available via extensions. We will
1102 1102 progressively enable these features by default in the next few releases, and
1103 1103 contribution is welcomed.
1104 1104
1105 1105 We welcome any feedback on the API. See :ref:`shell_mimerenderer` for more
1106 1106 informations.
1107 1107
1108 1108 This is originally based on work form in :ghpull:`10610` from @stephanh42
1109 1109 started over two years ago, and still a lot need to be done.
1110 1110
1111 1111 MISC
1112 1112 ----
1113 1113
1114 1114 - Completions can define their own ordering :ghpull:`11855`
1115 1115 - Enable Plotting in the same cell than the one that import matplotlib
1116 1116 :ghpull:`11916`
1117 1117 - Allow to store and restore multiple variables at once :ghpull:`11930`
1118 1118
1119 1119 You can see `all pull-requests <https://github.com/ipython/ipython/pulls?q=is%3Apr+milestone%3A7.10+is%3Aclosed>`_ for this release.
1120 1120
1121 1121 API Changes
1122 1122 -----------
1123 1123
1124 1124 Change of API and exposed objects automatically detected using `frappuccino <https://pypi.org/project/frappuccino/>`_ (still in beta):
1125 1125
1126 1126 The following items are new in IPython 7.10::
1127 1127
1128 1128 + IPython.terminal.shortcuts.reformat_text_before_cursor(buffer, document, shell)
1129 1129 + IPython.terminal.interactiveshell.PTK3
1130 1130 + IPython.terminal.interactiveshell.black_reformat_handler(text_before_cursor)
1131 1131 + IPython.terminal.prompts.RichPromptDisplayHook.write_format_data(self, format_dict, md_dict='None')
1132 1132
1133 1133 The following items have been removed in 7.10::
1134 1134
1135 1135 - IPython.lib.pretty.DICT_IS_ORDERED
1136 1136
1137 1137 The following signatures differ between versions::
1138 1138
1139 1139 - IPython.extensions.storemagic.restore_aliases(ip)
1140 1140 + IPython.extensions.storemagic.restore_aliases(ip, alias='None')
1141 1141
1142 1142 Special Thanks
1143 1143 --------------
1144 1144
1145 1145 - @stephanh42 who started the work on inline images in terminal 2 years ago
1146 1146 - @augustogoulart who spent a lot of time triaging issues and responding to
1147 1147 users.
1148 1148 - @con-f-use who is my (@Carreau) first sponsor on GitHub, as a reminder if you
1149 1149 like IPython, Jupyter and many other library of the SciPy stack you can
1150 1150 donate to numfocus.org non profit
1151 1151
1152 1152 .. _version 790:
1153 1153
1154 1154 IPython 7.9.0
1155 1155 =============
1156 1156
1157 1157 IPython 7.9 is a small release with a couple of improvement and bug fixes.
1158 1158
1159 1159 - Xterm terminal title should be restored on exit :ghpull:`11910`
1160 1160 - special variables ``_``,``__``, ``___`` are not set anymore when cache size
1161 1161 is 0 or less. :ghpull:`11877`
1162 1162 - Autoreload should have regained some speed by using a new heuristic logic to
1163 1163 find all objects needing reload. This should avoid large objects traversal
1164 1164 like pandas dataframes. :ghpull:`11876`
1165 1165 - Get ready for Python 4. :ghpull:`11874`
1166 1166 - `%env` Magic now has heuristic to hide potentially sensitive values :ghpull:`11896`
1167 1167
1168 1168 This is a small release despite a number of Pull Request Pending that need to
1169 1169 be reviewed/worked on. Many of the core developers have been busy outside of
1170 1170 IPython/Jupyter and we thanks all contributor for their patience; we'll work on
1171 1171 these as soon as we have time.
1172 1172
1173 1173
1174 1174 .. _version780:
1175 1175
1176 1176 IPython 7.8.0
1177 1177 =============
1178 1178
1179 1179 IPython 7.8.0 contain a few bugfix and 2 new APIs:
1180 1180
1181 1181 - Enable changing the font color for LaTeX rendering :ghpull:`11840`
1182 1182 - and Re-Expose some PDB API (see below)
1183 1183
1184 1184 Expose Pdb API
1185 1185 --------------
1186 1186
1187 1187 Expose the built-in ``pdb.Pdb`` API. ``Pdb`` constructor arguments are generically
1188 1188 exposed, regardless of python version.
1189 1189 Newly exposed arguments:
1190 1190
1191 1191 - ``skip`` - Python 3.1+
1192 1192 - ``nosiginnt`` - Python 3.2+
1193 1193 - ``readrc`` - Python 3.6+
1194 1194
1195 1195 Try it out::
1196 1196
1197 1197 from IPython.terminal.debugger import TerminalPdb
1198 1198 pdb = TerminalPdb(skip=["skipthismodule"])
1199 1199
1200 1200
1201 1201 See :ghpull:`11840`
1202 1202
1203 1203 .. _version770:
1204 1204
1205 1205 IPython 7.7.0
1206 1206 =============
1207 1207
1208 1208 IPython 7.7.0 contain multiple bug fixes and documentation updates; Here are a
1209 1209 few of the outstanding issue fixed:
1210 1210
1211 1211 - Fix a bug introduced in 7.6 where the ``%matplotlib`` magic would fail on
1212 1212 previously acceptable arguments :ghpull:`11814`.
1213 1213 - Fix the manage location on freebsd :ghpull:`11808`.
1214 1214 - Fix error message about aliases after ``%reset`` call in ipykernel
1215 1215 :ghpull:`11806`
1216 1216 - Fix Duplication completions in emacs :ghpull:`11803`
1217 1217
1218 1218 We are planning to adopt `NEP29 <https://github.com/numpy/numpy/pull/14086>`_
1219 1219 (still currently in draft) which may make this minor version of IPython the
1220 1220 last one to support Python 3.5 and will make the code base more aggressive
1221 1221 toward removing compatibility with older versions of Python.
1222 1222
1223 1223 GitHub now support to give only "Triage" permissions to users; if you'd like to
1224 1224 help close stale issues and labels issues please reach to us with your GitHub
1225 1225 Username and we'll add you to the triage team. It is a great way to start
1226 1226 contributing and a path toward getting commit rights.
1227 1227
1228 1228 .. _version761:
1229 1229
1230 1230 IPython 7.6.1
1231 1231 =============
1232 1232
1233 1233 IPython 7.6.1 contain a critical bugfix in the ``%timeit`` magic, which would
1234 1234 crash on some inputs as a side effect of :ghpull:`11716`. See :ghpull:`11812`
1235 1235
1236 1236
1237 1237 .. _whatsnew760:
1238 1238
1239 1239 IPython 7.6.0
1240 1240 =============
1241 1241
1242 1242 IPython 7.6.0 contains a couple of bug fixes and number of small features
1243 1243 additions as well as some compatibility with the current development version of
1244 1244 Python 3.8.
1245 1245
1246 1246 - Add a ``-l`` option to :magic:`psearch` to list the available search
1247 1247 types. :ghpull:`11672`
1248 1248 - Support ``PathLike`` for ``DisplayObject`` and ``Image``. :ghpull:`11764`
1249 1249 - Configurability of timeout in the test suite for slow platforms.
1250 1250 :ghpull:`11756`
1251 1251 - Accept any casing for matplotlib backend. :ghpull:`121748`
1252 1252 - Properly skip test that requires numpy to be installed :ghpull:`11723`
1253 1253 - More support for Python 3.8 and positional only arguments (pep570)
1254 1254 :ghpull:`11720`
1255 1255 - Unicode names for the completion are loaded lazily on first use which
1256 1256 should decrease startup time. :ghpull:`11693`
1257 1257 - Autoreload now update the types of reloaded objects; this for example allow
1258 1258 pickling of reloaded objects. :ghpull:`11644`
1259 1259 - Fix a bug where ``%%time`` magic would suppress cell output. :ghpull:`11716`
1260 1260
1261 1261
1262 1262 Prepare migration to pytest (instead of nose) for testing
1263 1263 ---------------------------------------------------------
1264 1264
1265 1265 Most of the work between 7.5 and 7.6 was to prepare the migration from our
1266 1266 testing framework to pytest. Most of the test suite should now work by simply
1267 1267 issuing ``pytest`` from the root of the repository.
1268 1268
1269 1269 The migration to pytest is just at its beginning. Many of our test still rely
1270 1270 on IPython-specific plugins for nose using pytest (doctest using IPython syntax
1271 1271 is one example of this where test appear as "passing", while no code has been
1272 1272 ran). Many test also need to be updated like ``yield-test`` to be properly
1273 1273 parametrized tests.
1274 1274
1275 1275 Migration to pytest allowed me to discover a number of issues in our test
1276 1276 suite; which was hiding a number of subtle issues – or not actually running
1277 1277 some of the tests in our test suite – I have thus corrected many of those; like
1278 1278 improperly closed resources; or used of deprecated features. I also made use of
1279 1279 the ``pytest --durations=...`` to find some of our slowest test and speed them
1280 1280 up (our test suite can now be up to 10% faster). Pytest as also a variety of
1281 1281 plugins and flags which will make the code quality of IPython and the testing
1282 1282 experience better.
1283 1283
1284 1284 Misc
1285 1285 ----
1286 1286
1287 1287 We skipped the release of 7.6 at the end of May, but will attempt to get back
1288 1288 on schedule. We are starting to think about making introducing backward
1289 1289 incompatible change and start the 8.0 series.
1290 1290
1291 1291 Special Thanks to Gabriel (@gpotter2 on GitHub), who among other took care many
1292 1292 of the remaining task for 7.4 and 7.5, like updating the website.
1293 1293
1294 1294 .. _whatsnew750:
1295 1295
1296 1296 IPython 7.5.0
1297 1297 =============
1298 1298
1299 1299 IPython 7.5.0 consist mostly of bug-fixes, and documentation updates, with one
1300 1300 minor new feature. The `Audio` display element can now be assigned an element
1301 1301 id when displayed in browser. See :ghpull:`11670`
1302 1302
1303 1303 The major outstanding bug fix correct a change of behavior that was introduce
1304 1304 in 7.4.0 where some cell magics would not be able to access or modify global
1305 1305 scope when using the ``@needs_local_scope`` decorator. This was typically
1306 1306 encountered with the ``%%time`` and ``%%timeit`` magics. See :ghissue:`11659`
1307 1307 and :ghpull:`11698`.
1308 1308
1309 1309 .. _whatsnew740:
1310 1310
1311 1311 IPython 7.4.0
1312 1312 =============
1313 1313
1314 1314 Unicode name completions
1315 1315 ------------------------
1316 1316
1317 1317 Previously, we provided completion for a unicode name with its relative symbol.
1318 1318 With this, now IPython provides complete suggestions to unicode name symbols.
1319 1319
1320 1320 As on the PR, if user types ``\LAT<tab>``, IPython provides a list of
1321 1321 possible completions. In this case, it would be something like::
1322 1322
1323 1323 'LATIN CAPITAL LETTER A',
1324 1324 'LATIN CAPITAL LETTER B',
1325 1325 'LATIN CAPITAL LETTER C',
1326 1326 'LATIN CAPITAL LETTER D',
1327 1327 ....
1328 1328
1329 1329 This help to type unicode character that do not have short latex aliases, and
1330 1330 have long unicode names. for example ``Ν°``, ``\GREEK CAPITAL LETTER HETA``.
1331 1331
1332 1332 This feature was contributed by Luciana Marques :ghpull:`11583`.
1333 1333
1334 1334 Make audio normalization optional
1335 1335 ---------------------------------
1336 1336
1337 1337 Added 'normalize' argument to `IPython.display.Audio`. This argument applies
1338 1338 when audio data is given as an array of samples. The default of `normalize=True`
1339 1339 preserves prior behavior of normalizing the audio to the maximum possible range.
1340 1340 Setting to `False` disables normalization.
1341 1341
1342 1342
1343 1343 Miscellaneous
1344 1344 -------------
1345 1345
1346 1346 - Fix improper acceptation of ``return`` outside of functions. :ghpull:`11641`.
1347 1347 - Fixed PyQt 5.11 backwards incompatibility causing sip import failure.
1348 1348 :ghpull:`11613`.
1349 1349 - Fix Bug where ``type?`` would crash IPython. :ghpull:`1608`.
1350 1350 - Allow to apply ``@needs_local_scope`` to cell magics for convenience.
1351 1351 :ghpull:`11542`.
1352 1352
1353 1353 .. _whatsnew730:
1354 1354
1355 1355 IPython 7.3.0
1356 1356 =============
1357 1357
1358 1358 .. _whatsnew720:
1359 1359
1360 1360 IPython 7.3.0 bring several bug fixes and small improvements that you will
1361 1361 described bellow.
1362 1362
1363 1363 The biggest change to this release is the implementation of the ``%conda`` and
1364 1364 ``%pip`` magics, that will attempt to install packages in the **current
1365 1365 environment**. You may still need to restart your interpreter or kernel for the
1366 1366 change to be taken into account, but it should simplify installation of packages
1367 1367 into remote environment. Installing using pip/conda from the command line is
1368 1368 still the prefer method.
1369 1369
1370 1370 The ``%pip`` magic was already present, but was only printing a warning; now it
1371 1371 will actually forward commands to pip.
1372 1372
1373 1373 Misc bug fixes and improvements:
1374 1374
1375 1375 - Compatibility with Python 3.8.
1376 1376 - Do not expand shell variable in execution magics, and added the
1377 1377 ``no_var_expand`` decorator for magic requiring a similar functionality
1378 1378 :ghpull:`11516`
1379 1379 - Add ``%pip`` and ``%conda`` magic :ghpull:`11524`
1380 1380 - Re-initialize posix aliases after a ``%reset`` :ghpull:`11528`
1381 1381 - Allow the IPython command line to run ``*.ipynb`` files :ghpull:`11529`
1382 1382
1383 1383 IPython 7.2.0
1384 1384 =============
1385 1385
1386 1386 IPython 7.2.0 brings minor bugfixes, improvements, and new configuration options:
1387 1387
1388 1388 - Fix a bug preventing PySide2 GUI integration from working :ghpull:`11464`
1389 1389 - Run CI on Mac OS ! :ghpull:`11471`
1390 1390 - Fix IPython "Demo" mode. :ghpull:`11498`
1391 1391 - Fix ``%run`` magic with path in name :ghpull:`11499`
1392 1392 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
1393 1393 - Better rendering of signatures, especially long ones. :ghpull:`11505`
1394 1394 - Re-enable jedi by default if it's installed :ghpull:`11506`
1395 1395 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
1396 1396
1397 1397
1398 1398 Added ability to show subclasses when using pinfo and other utilities
1399 1399 ---------------------------------------------------------------------
1400 1400
1401 1401 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
1402 1402
1403 1403 Special Thanks to Chris Mentzel of the Moore Foundation for this feature. Chris
1404 1404 is one of the people who played a critical role in IPython/Jupyter getting
1405 1405 funding.
1406 1406
1407 1407 We are grateful for all the help Chris has given us over the years,
1408 1408 and we're now proud to have code contributed by Chris in IPython.
1409 1409
1410 1410 OSMagics.cd_force_quiet configuration option
1411 1411 --------------------------------------------
1412 1412
1413 1413 You can set this option to force the %cd magic to behave as if ``-q`` was passed:
1414 1414 ::
1415 1415
1416 1416 In [1]: cd /
1417 1417 /
1418 1418
1419 1419 In [2]: %config OSMagics.cd_force_quiet = True
1420 1420
1421 1421 In [3]: cd /tmp
1422 1422
1423 1423 In [4]:
1424 1424
1425 1425 See :ghpull:`11491`
1426 1426
1427 1427 In vi editing mode, whether the prompt includes the current vi mode can now be configured
1428 1428 -----------------------------------------------------------------------------------------
1429 1429
1430 1430 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
1431 1431 (default: True) to control this feature. See :ghpull:`11492`
1432 1432
1433 1433 .. _whatsnew710:
1434 1434
1435 1435 IPython 7.1.0
1436 1436 =============
1437 1437
1438 1438 IPython 7.1.0 is the first minor release after 7.0.0 and mostly brings fixes to
1439 1439 new features, internal refactoring, and fixes for regressions that happened during the 6.x->7.x
1440 1440 transition. It also brings **Compatibility with Python 3.7.1**, as we're
1441 1441 unwillingly relying on a bug in CPython.
1442 1442
1443 1443 New Core Dev:
1444 1444
1445 1445 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
1446 1446 work on prompt_toolkit, and we'd like to recognise his impact by giving him
1447 1447 commit rights. :ghissue:`11397`
1448 1448
1449 1449 Notable Changes
1450 1450
1451 1451 - Major update of "latex to unicode" tab completion map (see below)
1452 1452
1453 1453 Notable New Features:
1454 1454
1455 1455 - Restore functionality and documentation of the **sphinx directive**, which
1456 1456 is now stricter (fail on error by daefault), has new configuration options,
1457 1457 has a brand new documentation page :ref:`ipython_directive` (which needs
1458 1458 some cleanup). It is also now *tested* so we hope to have less regressions.
1459 1459 :ghpull:`11402`
1460 1460
1461 1461 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
1462 1462 allowing a custom width and height to be set instead of using the video's
1463 1463 width and height. :ghpull:`11353`
1464 1464
1465 1465 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
1466 1466
1467 1467 - Allow Dynamic switching of editing mode between vi/emacs and show
1468 1468 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
1469 1469 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
1470 1470 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically switch
1471 1471 between modes.
1472 1472
1473 1473
1474 1474 Notable Fixes:
1475 1475
1476 1476 - Fix entering of **multi-line blocks in terminal** IPython, and various
1477 1477 crashes in the new input transformation machinery :ghpull:`11354`,
1478 1478 :ghpull:`11356`, :ghpull:`11358`. These also fix a **Compatibility bug
1479 1479 with Python 3.7.1**.
1480 1480
1481 1481 - Fix moving through generator stack in ipdb :ghpull:`11266`
1482 1482
1483 1483 - %Magic command arguments now support quoting. :ghpull:`11330`
1484 1484
1485 1485 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
1486 1486
1487 1487 - Remove implicit dependency on ``ipython_genutils`` :ghpull:`11317`
1488 1488
1489 1489 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
1490 1490 mode. :ghpull:`11382`
1491 1491
1492 1492 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
1493 1493 nested code blocks :ghpull:`11418`
1494 1494
1495 1495 - Fix instructions for custom shortcuts :ghpull:`11426`
1496 1496
1497 1497
1498 1498 Notable Internals improvements:
1499 1499
1500 1500 - Use of ``os.scandir`` (Python 3 only) to speed up some file system operations.
1501 1501 :ghpull:`11365`
1502 1502
1503 1503 - use ``perf_counter`` instead of ``clock`` for more precise
1504 1504 timing results with ``%time`` :ghpull:`11376`
1505 1505
1506 1506 Many thanks to all the contributors and in particular to ``bartskowron`` and
1507 1507 ``tonyfast`` who handled some pretty complicated bugs in the input machinery. We
1508 1508 had a number of first time contributors and maybe hacktoberfest participants that
1509 1509 made significant contributions and helped us free some time to focus on more
1510 1510 complicated bugs.
1511 1511
1512 1512 You
1513 1513 can see all the closed issues and Merged PR, new features and fixes `here
1514 1514 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
1515 1515
1516 1516 Unicode Completion update
1517 1517 -------------------------
1518 1518
1519 1519 In IPython 7.1 the Unicode completion map has been updated and synchronized with
1520 1520 the Julia language.
1521 1521
1522 1522 Added and removed character characters:
1523 1523
1524 1524 ``\jmath`` (``Θ·``), ``\\underleftrightarrow`` (U+034D, combining) have been
1525 1525 added, while ``\\textasciicaron`` have been removed
1526 1526
1527 1527 Some sequences have seen their prefix removed:
1528 1528
1529 1529 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
1530 1530 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
1531 1531 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
1532 1532 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
1533 1533
1534 1534 Some sequences have seen their prefix shortened:
1535 1535
1536 1536 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
1537 1537 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
1538 1538 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
1539 1539 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
1540 1540
1541 1541 A couple of characters had their sequence simplified:
1542 1542
1543 1543 - ``Γ°``, type ``\dh<tab>``, instead of ``\eth<tab>``
1544 1544 - ``Δ§``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
1545 1545 - ``ΙΈ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
1546 1546 - ``Ο΄``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
1547 1547 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
1548 1548 - ``β„Ž``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
1549 1549
1550 1550 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
1551 1551
1552 1552 A couple of sequences have been updated:
1553 1553
1554 1554 - ``\varepsilon`` now gives ``Ι›`` (GREEK SMALL LETTER EPSILON) instead of ``Ξ΅`` (GREEK LUNATE EPSILON SYMBOL),
1555 1555 - ``\underbar`` now gives U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
1556 1556
1557 1557
1558 1558 .. _whatsnew700:
1559 1559
1560 1560 IPython 7.0.0
1561 1561 =============
1562 1562
1563 1563 Released Thursday September 27th, 2018
1564 1564
1565 1565 IPython 7 includes major feature improvements.
1566 1566 This is also the second major version of IPython to support only
1567 1567 Python 3 – starting at Python 3.4. Python 2 is still community-supported
1568 1568 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
1569 1569 is on Jan 1st 2020.
1570 1570
1571 1571 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
1572 1572 backported more than `70 Pull-Requests
1573 1573 <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>`_
1574 1574
1575 1575 The IPython 6.x branch will likely not see any further release unless critical
1576 1576 bugs are found.
1577 1577
1578 1578 Make sure you have pip > 9.0 before upgrading. You should be able to update by running:
1579 1579
1580 1580 .. code::
1581 1581
1582 1582 pip install ipython --upgrade
1583 1583
1584 1584 .. only:: ipydev
1585 1585
1586 1586 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
1587 1587 version, use pip ``--pre`` flag.
1588 1588
1589 1589 .. code::
1590 1590
1591 1591 pip install ipython --upgrade --pre
1592 1592
1593 1593
1594 1594 Or, if you have conda installed:
1595 1595
1596 1596 .. code::
1597 1597
1598 1598 conda install ipython
1599 1599
1600 1600
1601 1601
1602 1602 Prompt Toolkit 2.0
1603 1603 ------------------
1604 1604
1605 1605 IPython 7.0+ now uses ``prompt_toolkit 2.0``. If you still need to use an earlier
1606 1606 ``prompt_toolkit`` version, you may need to pin IPython to ``<7.0``.
1607 1607
1608 1608 Autowait: Asynchronous REPL
1609 1609 ---------------------------
1610 1610
1611 1611 Staring with IPython 7.0 on Python 3.6+, IPython can automatically ``await``
1612 1612 top level code. You should not need to access an event loop or runner
1613 1613 yourself. To learn more, read the :ref:`autoawait` section of our docs, see
1614 1614 :ghpull:`11265`, or try the following code::
1615 1615
1616 1616 Python 3.6.0
1617 1617 Type 'copyright', 'credits' or 'license' for more information
1618 1618 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
1619 1619
1620 1620 In [1]: import aiohttp
1621 1621 ...: result = aiohttp.get('https://api.github.com')
1622 1622
1623 1623 In [2]: response = await result
1624 1624 <pause for a few 100s ms>
1625 1625
1626 1626 In [3]: await response.json()
1627 1627 Out[3]:
1628 1628 {'authorizations_url': 'https://api.github.com/authorizations',
1629 1629 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
1630 1630 ...
1631 1631 }
1632 1632
1633 1633 .. note::
1634 1634
1635 1635 Async integration is experimental code, behavior may change or be removed
1636 1636 between Python and IPython versions without warnings.
1637 1637
1638 1638 Integration is by default with `asyncio`, but other libraries can be configured --
1639 1639 like ``curio`` or ``trio`` -- to improve concurrency in the REPL::
1640 1640
1641 1641 In [1]: %autoawait trio
1642 1642
1643 1643 In [2]: import trio
1644 1644
1645 1645 In [3]: async def child(i):
1646 1646 ...: print(" child %s goes to sleep"%i)
1647 1647 ...: await trio.sleep(2)
1648 1648 ...: print(" child %s wakes up"%i)
1649 1649
1650 1650 In [4]: print('parent start')
1651 1651 ...: async with trio.open_nursery() as n:
1652 1652 ...: for i in range(3):
1653 1653 ...: n.spawn(child, i)
1654 1654 ...: print('parent end')
1655 1655 parent start
1656 1656 child 2 goes to sleep
1657 1657 child 0 goes to sleep
1658 1658 child 1 goes to sleep
1659 1659 <about 2 seconds pause>
1660 1660 child 2 wakes up
1661 1661 child 1 wakes up
1662 1662 child 0 wakes up
1663 1663 parent end
1664 1664
1665 1665 See :ref:`autoawait` for more information.
1666 1666
1667 1667
1668 1668 Asynchronous code in a Notebook interface or any other frontend using the
1669 1669 Jupyter Protocol will require further updates to the IPykernel package.
1670 1670
1671 1671 Non-Asynchronous code
1672 1672 ~~~~~~~~~~~~~~~~~~~~~
1673 1673
1674 1674 As the internal API of IPython is now asynchronous, IPython needs to run under
1675 1675 an event loop. In order to allow many workflows, (like using the :magic:`%run`
1676 1676 magic, or copy-pasting code that explicitly starts/stop event loop), when
1677 1677 top-level code is detected as not being asynchronous, IPython code is advanced
1678 1678 via a pseudo-synchronous runner, and may not advance pending tasks.
1679 1679
1680 1680 Change to Nested Embed
1681 1681 ~~~~~~~~~~~~~~~~~~~~~~
1682 1682
1683 1683 The introduction of the ability to run async code had some effect on the
1684 1684 ``IPython.embed()`` API. By default, embed will not allow you to run asynchronous
1685 1685 code unless an event loop is specified.
1686 1686
1687 1687 Effects on Magics
1688 1688 ~~~~~~~~~~~~~~~~~
1689 1689
1690 1690 Some magics will not work with async until they're updated.
1691 1691 Contributions welcome.
1692 1692
1693 1693 Expected Future changes
1694 1694 ~~~~~~~~~~~~~~~~~~~~~~~
1695 1695
1696 1696 We expect more internal but public IPython functions to become ``async``, and
1697 1697 will likely end up having a persistent event loop while IPython is running.
1698 1698
1699 1699 Thanks
1700 1700 ~~~~~~
1701 1701
1702 1702 This release took more than a year in the making.
1703 1703 The code was rebased a number of
1704 1704 times; leading to commit authorship that may have been lost in the final
1705 1705 Pull-Request. Huge thanks to many people for contribution, discussion, code,
1706 1706 documentation, use-cases: dalejung, danielballan, ellisonbg, fperez, gnestor,
1707 1707 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
1708 1708
1709 1709
1710 1710 Autoreload Improvement
1711 1711 ----------------------
1712 1712
1713 1713 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
1714 1714 classes. Earlier, only methods existing as of the initial import were being
1715 1715 tracked and updated.
1716 1716
1717 1717 This new feature helps dual environment development - Jupyter+IDE - where the
1718 1718 code gradually moves from notebook cells to package files as it gets
1719 1719 structured.
1720 1720
1721 1721 **Example**: An instance of the class ``MyClass`` will be able to access the
1722 1722 method ``cube()`` after it is uncommented and the file ``file1.py`` is saved on
1723 1723 disk.
1724 1724
1725 1725
1726 1726 .. code::
1727 1727
1728 1728 # notebook
1729 1729
1730 1730 from mymodule import MyClass
1731 1731 first = MyClass(5)
1732 1732
1733 1733 .. code::
1734 1734
1735 1735 # mymodule/file1.py
1736 1736
1737 1737 class MyClass:
1738 1738
1739 1739 def __init__(self, a=10):
1740 1740 self.a = a
1741 1741
1742 1742 def square(self):
1743 1743 print('compute square')
1744 1744 return self.a*self.a
1745 1745
1746 1746 # def cube(self):
1747 1747 # print('compute cube')
1748 1748 # return self.a*self.a*self.a
1749 1749
1750 1750
1751 1751
1752 1752
1753 1753 Misc
1754 1754 ----
1755 1755
1756 1756 The autoindent feature that was deprecated in 5.x was re-enabled and
1757 1757 un-deprecated in :ghpull:`11257`
1758 1758
1759 1759 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
1760 1760 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
1761 1761
1762 1762
1763 1763 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
1764 1764 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
1765 1765 the given code is non-zero (thus halting execution of further cells in a
1766 1766 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
1767 1767
1768 1768
1769 1769 Deprecations
1770 1770 ------------
1771 1771
1772 1772 A couple of unused functions and methods have been deprecated and will be removed
1773 1773 in future versions:
1774 1774
1775 1775 - ``IPython.utils.io.raw_print_err``
1776 1776 - ``IPython.utils.io.raw_print``
1777 1777
1778 1778
1779 1779 Backwards incompatible changes
1780 1780 ------------------------------
1781 1781
1782 1782 * The API for transforming input before it is parsed as Python code has been
1783 1783 completely redesigned: any custom input transformations will need to be
1784 1784 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