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