##// END OF EJS Templates
Update Matplotlib docs
Ian Thomas -
Show More
@@ -1,518 +1,522 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Pylab (matplotlib) support utilities."""
2 """Pylab (matplotlib) support utilities."""
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 from io import BytesIO
7 from io import BytesIO
8 from binascii import b2a_base64
8 from binascii import b2a_base64
9 from functools import partial
9 from functools import partial
10 import warnings
10 import warnings
11
11
12 from IPython.core.display import _pngxy
12 from IPython.core.display import _pngxy
13 from IPython.utils.decorators import flag_calls
13 from IPython.utils.decorators import flag_calls
14
14
15
15
16 # Matplotlib backend resolution functionality moved from IPython to Matplotlib
16 # Matplotlib backend resolution functionality moved from IPython to Matplotlib
17 # in IPython 8.24 and Matplotlib 3.9.1. Need to keep `backends` and `backend2gui`
17 # in IPython 8.24 and Matplotlib 3.9.0. Need to keep `backends` and `backend2gui`
18 # here for earlier Matplotlib and for external backend libraries such as
18 # here for earlier Matplotlib and for external backend libraries such as
19 # mplcairo that might rely upon it.
19 # mplcairo that might rely upon it.
20 _deprecated_backends = {
20 _deprecated_backends = {
21 "tk": "TkAgg",
21 "tk": "TkAgg",
22 "gtk": "GTKAgg",
22 "gtk": "GTKAgg",
23 "gtk3": "GTK3Agg",
23 "gtk3": "GTK3Agg",
24 "gtk4": "GTK4Agg",
24 "gtk4": "GTK4Agg",
25 "wx": "WXAgg",
25 "wx": "WXAgg",
26 "qt4": "Qt4Agg",
26 "qt4": "Qt4Agg",
27 "qt5": "Qt5Agg",
27 "qt5": "Qt5Agg",
28 "qt6": "QtAgg",
28 "qt6": "QtAgg",
29 "qt": "QtAgg",
29 "qt": "QtAgg",
30 "osx": "MacOSX",
30 "osx": "MacOSX",
31 "nbagg": "nbAgg",
31 "nbagg": "nbAgg",
32 "webagg": "WebAgg",
32 "webagg": "WebAgg",
33 "notebook": "nbAgg",
33 "notebook": "nbAgg",
34 "agg": "agg",
34 "agg": "agg",
35 "svg": "svg",
35 "svg": "svg",
36 "pdf": "pdf",
36 "pdf": "pdf",
37 "ps": "ps",
37 "ps": "ps",
38 "inline": "module://matplotlib_inline.backend_inline",
38 "inline": "module://matplotlib_inline.backend_inline",
39 "ipympl": "module://ipympl.backend_nbagg",
39 "ipympl": "module://ipympl.backend_nbagg",
40 "widget": "module://ipympl.backend_nbagg",
40 "widget": "module://ipympl.backend_nbagg",
41 }
41 }
42
42
43 # We also need a reverse backends2guis mapping that will properly choose which
43 # We also need a reverse backends2guis mapping that will properly choose which
44 # GUI support to activate based on the desired matplotlib backend. For the
44 # GUI support to activate based on the desired matplotlib backend. For the
45 # most part it's just a reverse of the above dict, but we also need to add a
45 # most part it's just a reverse of the above dict, but we also need to add a
46 # few others that map to the same GUI manually:
46 # few others that map to the same GUI manually:
47 _deprecated_backend2gui = dict(
47 _deprecated_backend2gui = dict(
48 zip(_deprecated_backends.values(), _deprecated_backends.keys())
48 zip(_deprecated_backends.values(), _deprecated_backends.keys())
49 )
49 )
50 # In the reverse mapping, there are a few extra valid matplotlib backends that
50 # In the reverse mapping, there are a few extra valid matplotlib backends that
51 # map to the same GUI support
51 # map to the same GUI support
52 _deprecated_backend2gui["GTK"] = _deprecated_backend2gui["GTKCairo"] = "gtk"
52 _deprecated_backend2gui["GTK"] = _deprecated_backend2gui["GTKCairo"] = "gtk"
53 _deprecated_backend2gui["GTK3Cairo"] = "gtk3"
53 _deprecated_backend2gui["GTK3Cairo"] = "gtk3"
54 _deprecated_backend2gui["GTK4Cairo"] = "gtk4"
54 _deprecated_backend2gui["GTK4Cairo"] = "gtk4"
55 _deprecated_backend2gui["WX"] = "wx"
55 _deprecated_backend2gui["WX"] = "wx"
56 _deprecated_backend2gui["CocoaAgg"] = "osx"
56 _deprecated_backend2gui["CocoaAgg"] = "osx"
57 # There needs to be a hysteresis here as the new QtAgg Matplotlib backend
57 # There needs to be a hysteresis here as the new QtAgg Matplotlib backend
58 # supports either Qt5 or Qt6 and the IPython qt event loop support Qt4, Qt5,
58 # supports either Qt5 or Qt6 and the IPython qt event loop support Qt4, Qt5,
59 # and Qt6.
59 # and Qt6.
60 _deprecated_backend2gui["QtAgg"] = "qt"
60 _deprecated_backend2gui["QtAgg"] = "qt"
61 _deprecated_backend2gui["Qt4Agg"] = "qt4"
61 _deprecated_backend2gui["Qt4Agg"] = "qt4"
62 _deprecated_backend2gui["Qt5Agg"] = "qt5"
62 _deprecated_backend2gui["Qt5Agg"] = "qt5"
63
63
64 # And some backends that don't need GUI integration
64 # And some backends that don't need GUI integration
65 del _deprecated_backend2gui["nbAgg"]
65 del _deprecated_backend2gui["nbAgg"]
66 del _deprecated_backend2gui["agg"]
66 del _deprecated_backend2gui["agg"]
67 del _deprecated_backend2gui["svg"]
67 del _deprecated_backend2gui["svg"]
68 del _deprecated_backend2gui["pdf"]
68 del _deprecated_backend2gui["pdf"]
69 del _deprecated_backend2gui["ps"]
69 del _deprecated_backend2gui["ps"]
70 del _deprecated_backend2gui["module://matplotlib_inline.backend_inline"]
70 del _deprecated_backend2gui["module://matplotlib_inline.backend_inline"]
71 del _deprecated_backend2gui["module://ipympl.backend_nbagg"]
71 del _deprecated_backend2gui["module://ipympl.backend_nbagg"]
72
72
73
73
74 # Deprecated attributes backends and backend2gui mostly following PEP 562.
74 # Deprecated attributes backends and backend2gui mostly following PEP 562.
75 def __getattr__(name):
75 def __getattr__(name):
76 if name in ("backends", "backend2gui"):
76 if name in ("backends", "backend2gui"):
77 warnings.warn(
77 warnings.warn(
78 f"{name} is deprecated since IPython 8.24, backends are managed "
78 f"{name} is deprecated since IPython 8.24, backends are managed "
79 "in matplotlib and can be externally registered.",
79 "in matplotlib and can be externally registered.",
80 DeprecationWarning,
80 DeprecationWarning,
81 )
81 )
82 return globals()[f"_deprecated_{name}"]
82 return globals()[f"_deprecated_{name}"]
83 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
83 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
84
84
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Matplotlib utilities
87 # Matplotlib utilities
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90
90
91 def getfigs(*fig_nums):
91 def getfigs(*fig_nums):
92 """Get a list of matplotlib figures by figure numbers.
92 """Get a list of matplotlib figures by figure numbers.
93
93
94 If no arguments are given, all available figures are returned. If the
94 If no arguments are given, all available figures are returned. If the
95 argument list contains references to invalid figures, a warning is printed
95 argument list contains references to invalid figures, a warning is printed
96 but the function continues pasting further figures.
96 but the function continues pasting further figures.
97
97
98 Parameters
98 Parameters
99 ----------
99 ----------
100 figs : tuple
100 figs : tuple
101 A tuple of ints giving the figure numbers of the figures to return.
101 A tuple of ints giving the figure numbers of the figures to return.
102 """
102 """
103 from matplotlib._pylab_helpers import Gcf
103 from matplotlib._pylab_helpers import Gcf
104 if not fig_nums:
104 if not fig_nums:
105 fig_managers = Gcf.get_all_fig_managers()
105 fig_managers = Gcf.get_all_fig_managers()
106 return [fm.canvas.figure for fm in fig_managers]
106 return [fm.canvas.figure for fm in fig_managers]
107 else:
107 else:
108 figs = []
108 figs = []
109 for num in fig_nums:
109 for num in fig_nums:
110 f = Gcf.figs.get(num)
110 f = Gcf.figs.get(num)
111 if f is None:
111 if f is None:
112 print('Warning: figure %s not available.' % num)
112 print('Warning: figure %s not available.' % num)
113 else:
113 else:
114 figs.append(f.canvas.figure)
114 figs.append(f.canvas.figure)
115 return figs
115 return figs
116
116
117
117
118 def figsize(sizex, sizey):
118 def figsize(sizex, sizey):
119 """Set the default figure size to be [sizex, sizey].
119 """Set the default figure size to be [sizex, sizey].
120
120
121 This is just an easy to remember, convenience wrapper that sets::
121 This is just an easy to remember, convenience wrapper that sets::
122
122
123 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
123 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
124 """
124 """
125 import matplotlib
125 import matplotlib
126 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
126 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
127
127
128
128
129 def print_figure(fig, fmt="png", bbox_inches="tight", base64=False, **kwargs):
129 def print_figure(fig, fmt="png", bbox_inches="tight", base64=False, **kwargs):
130 """Print a figure to an image, and return the resulting file data
130 """Print a figure to an image, and return the resulting file data
131
131
132 Returned data will be bytes unless ``fmt='svg'``,
132 Returned data will be bytes unless ``fmt='svg'``,
133 in which case it will be unicode.
133 in which case it will be unicode.
134
134
135 Any keyword args are passed to fig.canvas.print_figure,
135 Any keyword args are passed to fig.canvas.print_figure,
136 such as ``quality`` or ``bbox_inches``.
136 such as ``quality`` or ``bbox_inches``.
137
137
138 If `base64` is True, return base64-encoded str instead of raw bytes
138 If `base64` is True, return base64-encoded str instead of raw bytes
139 for binary-encoded image formats
139 for binary-encoded image formats
140
140
141 .. versionadded:: 7.29
141 .. versionadded:: 7.29
142 base64 argument
142 base64 argument
143 """
143 """
144 # When there's an empty figure, we shouldn't return anything, otherwise we
144 # When there's an empty figure, we shouldn't return anything, otherwise we
145 # get big blank areas in the qt console.
145 # get big blank areas in the qt console.
146 if not fig.axes and not fig.lines:
146 if not fig.axes and not fig.lines:
147 return
147 return
148
148
149 dpi = fig.dpi
149 dpi = fig.dpi
150 if fmt == 'retina':
150 if fmt == 'retina':
151 dpi = dpi * 2
151 dpi = dpi * 2
152 fmt = 'png'
152 fmt = 'png'
153
153
154 # build keyword args
154 # build keyword args
155 kw = {
155 kw = {
156 "format":fmt,
156 "format":fmt,
157 "facecolor":fig.get_facecolor(),
157 "facecolor":fig.get_facecolor(),
158 "edgecolor":fig.get_edgecolor(),
158 "edgecolor":fig.get_edgecolor(),
159 "dpi":dpi,
159 "dpi":dpi,
160 "bbox_inches":bbox_inches,
160 "bbox_inches":bbox_inches,
161 }
161 }
162 # **kwargs get higher priority
162 # **kwargs get higher priority
163 kw.update(kwargs)
163 kw.update(kwargs)
164
164
165 bytes_io = BytesIO()
165 bytes_io = BytesIO()
166 if fig.canvas is None:
166 if fig.canvas is None:
167 from matplotlib.backend_bases import FigureCanvasBase
167 from matplotlib.backend_bases import FigureCanvasBase
168 FigureCanvasBase(fig)
168 FigureCanvasBase(fig)
169
169
170 fig.canvas.print_figure(bytes_io, **kw)
170 fig.canvas.print_figure(bytes_io, **kw)
171 data = bytes_io.getvalue()
171 data = bytes_io.getvalue()
172 if fmt == 'svg':
172 if fmt == 'svg':
173 data = data.decode('utf-8')
173 data = data.decode('utf-8')
174 elif base64:
174 elif base64:
175 data = b2a_base64(data, newline=False).decode("ascii")
175 data = b2a_base64(data, newline=False).decode("ascii")
176 return data
176 return data
177
177
178 def retina_figure(fig, base64=False, **kwargs):
178 def retina_figure(fig, base64=False, **kwargs):
179 """format a figure as a pixel-doubled (retina) PNG
179 """format a figure as a pixel-doubled (retina) PNG
180
180
181 If `base64` is True, return base64-encoded str instead of raw bytes
181 If `base64` is True, return base64-encoded str instead of raw bytes
182 for binary-encoded image formats
182 for binary-encoded image formats
183
183
184 .. versionadded:: 7.29
184 .. versionadded:: 7.29
185 base64 argument
185 base64 argument
186 """
186 """
187 pngdata = print_figure(fig, fmt="retina", base64=False, **kwargs)
187 pngdata = print_figure(fig, fmt="retina", base64=False, **kwargs)
188 # Make sure that retina_figure acts just like print_figure and returns
188 # Make sure that retina_figure acts just like print_figure and returns
189 # None when the figure is empty.
189 # None when the figure is empty.
190 if pngdata is None:
190 if pngdata is None:
191 return
191 return
192 w, h = _pngxy(pngdata)
192 w, h = _pngxy(pngdata)
193 metadata = {"width": w//2, "height":h//2}
193 metadata = {"width": w//2, "height":h//2}
194 if base64:
194 if base64:
195 pngdata = b2a_base64(pngdata, newline=False).decode("ascii")
195 pngdata = b2a_base64(pngdata, newline=False).decode("ascii")
196 return pngdata, metadata
196 return pngdata, metadata
197
197
198
198
199 # We need a little factory function here to create the closure where
199 # We need a little factory function here to create the closure where
200 # safe_execfile can live.
200 # safe_execfile can live.
201 def mpl_runner(safe_execfile):
201 def mpl_runner(safe_execfile):
202 """Factory to return a matplotlib-enabled runner for %run.
202 """Factory to return a matplotlib-enabled runner for %run.
203
203
204 Parameters
204 Parameters
205 ----------
205 ----------
206 safe_execfile : function
206 safe_execfile : function
207 This must be a function with the same interface as the
207 This must be a function with the same interface as the
208 :meth:`safe_execfile` method of IPython.
208 :meth:`safe_execfile` method of IPython.
209
209
210 Returns
210 Returns
211 -------
211 -------
212 A function suitable for use as the ``runner`` argument of the %run magic
212 A function suitable for use as the ``runner`` argument of the %run magic
213 function.
213 function.
214 """
214 """
215
215
216 def mpl_execfile(fname,*where,**kw):
216 def mpl_execfile(fname,*where,**kw):
217 """matplotlib-aware wrapper around safe_execfile.
217 """matplotlib-aware wrapper around safe_execfile.
218
218
219 Its interface is identical to that of the :func:`execfile` builtin.
219 Its interface is identical to that of the :func:`execfile` builtin.
220
220
221 This is ultimately a call to execfile(), but wrapped in safeties to
221 This is ultimately a call to execfile(), but wrapped in safeties to
222 properly handle interactive rendering."""
222 properly handle interactive rendering."""
223
223
224 import matplotlib
224 import matplotlib
225 import matplotlib.pyplot as plt
225 import matplotlib.pyplot as plt
226
226
227 #print '*** Matplotlib runner ***' # dbg
227 #print '*** Matplotlib runner ***' # dbg
228 # turn off rendering until end of script
228 # turn off rendering until end of script
229 with matplotlib.rc_context({"interactive": False}):
229 with matplotlib.rc_context({"interactive": False}):
230 safe_execfile(fname, *where, **kw)
230 safe_execfile(fname, *where, **kw)
231
231
232 if matplotlib.is_interactive():
232 if matplotlib.is_interactive():
233 plt.show()
233 plt.show()
234
234
235 # make rendering call now, if the user tried to do it
235 # make rendering call now, if the user tried to do it
236 if plt.draw_if_interactive.called:
236 if plt.draw_if_interactive.called:
237 plt.draw()
237 plt.draw()
238 plt.draw_if_interactive.called = False
238 plt.draw_if_interactive.called = False
239
239
240 # re-draw everything that is stale
240 # re-draw everything that is stale
241 try:
241 try:
242 da = plt.draw_all
242 da = plt.draw_all
243 except AttributeError:
243 except AttributeError:
244 pass
244 pass
245 else:
245 else:
246 da()
246 da()
247
247
248 return mpl_execfile
248 return mpl_execfile
249
249
250
250
251 def _reshow_nbagg_figure(fig):
251 def _reshow_nbagg_figure(fig):
252 """reshow an nbagg figure"""
252 """reshow an nbagg figure"""
253 try:
253 try:
254 reshow = fig.canvas.manager.reshow
254 reshow = fig.canvas.manager.reshow
255 except AttributeError as e:
255 except AttributeError as e:
256 raise NotImplementedError() from e
256 raise NotImplementedError() from e
257 else:
257 else:
258 reshow()
258 reshow()
259
259
260
260
261 def select_figure_formats(shell, formats, **kwargs):
261 def select_figure_formats(shell, formats, **kwargs):
262 """Select figure formats for the inline backend.
262 """Select figure formats for the inline backend.
263
263
264 Parameters
264 Parameters
265 ----------
265 ----------
266 shell : InteractiveShell
266 shell : InteractiveShell
267 The main IPython instance.
267 The main IPython instance.
268 formats : str or set
268 formats : str or set
269 One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
269 One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
270 **kwargs : any
270 **kwargs : any
271 Extra keyword arguments to be passed to fig.canvas.print_figure.
271 Extra keyword arguments to be passed to fig.canvas.print_figure.
272 """
272 """
273 import matplotlib
273 import matplotlib
274 from matplotlib.figure import Figure
274 from matplotlib.figure import Figure
275
275
276 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
276 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
277 png_formatter = shell.display_formatter.formatters['image/png']
277 png_formatter = shell.display_formatter.formatters['image/png']
278 jpg_formatter = shell.display_formatter.formatters['image/jpeg']
278 jpg_formatter = shell.display_formatter.formatters['image/jpeg']
279 pdf_formatter = shell.display_formatter.formatters['application/pdf']
279 pdf_formatter = shell.display_formatter.formatters['application/pdf']
280
280
281 if isinstance(formats, str):
281 if isinstance(formats, str):
282 formats = {formats}
282 formats = {formats}
283 # cast in case of list / tuple
283 # cast in case of list / tuple
284 formats = set(formats)
284 formats = set(formats)
285
285
286 [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]
286 [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]
287 mplbackend = matplotlib.get_backend().lower()
287 mplbackend = matplotlib.get_backend().lower()
288 if mplbackend in ("nbagg", "ipympl", "widget", "module://ipympl.backend_nbagg"):
288 if mplbackend in ("nbagg", "ipympl", "widget", "module://ipympl.backend_nbagg"):
289 formatter = shell.display_formatter.ipython_display_formatter
289 formatter = shell.display_formatter.ipython_display_formatter
290 formatter.for_type(Figure, _reshow_nbagg_figure)
290 formatter.for_type(Figure, _reshow_nbagg_figure)
291
291
292 supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}
292 supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}
293 bad = formats.difference(supported)
293 bad = formats.difference(supported)
294 if bad:
294 if bad:
295 bs = "%s" % ','.join([repr(f) for f in bad])
295 bs = "%s" % ','.join([repr(f) for f in bad])
296 gs = "%s" % ','.join([repr(f) for f in supported])
296 gs = "%s" % ','.join([repr(f) for f in supported])
297 raise ValueError("supported formats are: %s not %s" % (gs, bs))
297 raise ValueError("supported formats are: %s not %s" % (gs, bs))
298
298
299 if "png" in formats:
299 if "png" in formats:
300 png_formatter.for_type(
300 png_formatter.for_type(
301 Figure, partial(print_figure, fmt="png", base64=True, **kwargs)
301 Figure, partial(print_figure, fmt="png", base64=True, **kwargs)
302 )
302 )
303 if "retina" in formats or "png2x" in formats:
303 if "retina" in formats or "png2x" in formats:
304 png_formatter.for_type(Figure, partial(retina_figure, base64=True, **kwargs))
304 png_formatter.for_type(Figure, partial(retina_figure, base64=True, **kwargs))
305 if "jpg" in formats or "jpeg" in formats:
305 if "jpg" in formats or "jpeg" in formats:
306 jpg_formatter.for_type(
306 jpg_formatter.for_type(
307 Figure, partial(print_figure, fmt="jpg", base64=True, **kwargs)
307 Figure, partial(print_figure, fmt="jpg", base64=True, **kwargs)
308 )
308 )
309 if "svg" in formats:
309 if "svg" in formats:
310 svg_formatter.for_type(Figure, partial(print_figure, fmt="svg", **kwargs))
310 svg_formatter.for_type(Figure, partial(print_figure, fmt="svg", **kwargs))
311 if "pdf" in formats:
311 if "pdf" in formats:
312 pdf_formatter.for_type(
312 pdf_formatter.for_type(
313 Figure, partial(print_figure, fmt="pdf", base64=True, **kwargs)
313 Figure, partial(print_figure, fmt="pdf", base64=True, **kwargs)
314 )
314 )
315
315
316 #-----------------------------------------------------------------------------
316 #-----------------------------------------------------------------------------
317 # Code for initializing matplotlib and importing pylab
317 # Code for initializing matplotlib and importing pylab
318 #-----------------------------------------------------------------------------
318 #-----------------------------------------------------------------------------
319
319
320
320
321 def find_gui_and_backend(gui=None, gui_select=None):
321 def find_gui_and_backend(gui=None, gui_select=None):
322 """Given a gui string return the gui and mpl backend.
322 """Given a gui string return the gui and mpl backend.
323
323
324 Parameters
324 Parameters
325 ----------
325 ----------
326 gui : str
326 gui : str
327 Can be one of ('tk','gtk','wx','qt','qt4','inline','agg').
327 Can be one of ('tk','gtk','wx','qt','qt4','inline','agg').
328 gui_select : str
328 gui_select : str
329 Can be one of ('tk','gtk','wx','qt','qt4','inline').
329 Can be one of ('tk','gtk','wx','qt','qt4','inline').
330 This is any gui already selected by the shell.
330 This is any gui already selected by the shell.
331
331
332 Returns
332 Returns
333 -------
333 -------
334 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
334 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
335 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg').
335 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg').
336 """
336 """
337
337
338 import matplotlib
338 import matplotlib
339
339
340 if _matplotlib_manages_backends():
340 if _matplotlib_manages_backends():
341 backend_registry = matplotlib.backends.registry.backend_registry
341 backend_registry = matplotlib.backends.registry.backend_registry
342
342
343 # gui argument may be a gui event loop or may be a backend name.
343 # gui argument may be a gui event loop or may be a backend name.
344 if gui in ("auto", None):
344 if gui in ("auto", None):
345 backend = matplotlib.rcParamsOrig["backend"]
345 backend = matplotlib.rcParamsOrig["backend"]
346 backend, gui = backend_registry.resolve_backend(backend)
346 backend, gui = backend_registry.resolve_backend(backend)
347 else:
347 else:
348 backend, gui = backend_registry.resolve_gui_or_backend(gui)
348 backend, gui = backend_registry.resolve_gui_or_backend(gui)
349
349
350 return gui, backend
350 return gui, backend
351
351
352 # Fallback to previous behaviour (Matplotlib < 3.9)
352 # Fallback to previous behaviour (Matplotlib < 3.9)
353 mpl_version_info = getattr(matplotlib, "__version_info__", (0, 0))
353 mpl_version_info = getattr(matplotlib, "__version_info__", (0, 0))
354 has_unified_qt_backend = mpl_version_info >= (3, 5)
354 has_unified_qt_backend = mpl_version_info >= (3, 5)
355
355
356 from IPython.core.pylabtools import backends
356 from IPython.core.pylabtools import backends
357
357
358 backends_ = dict(backends)
358 backends_ = dict(backends)
359 if not has_unified_qt_backend:
359 if not has_unified_qt_backend:
360 backends_["qt"] = "qt5agg"
360 backends_["qt"] = "qt5agg"
361
361
362 if gui and gui != 'auto':
362 if gui and gui != 'auto':
363 # select backend based on requested gui
363 # select backend based on requested gui
364 backend = backends_[gui]
364 backend = backends_[gui]
365 if gui == 'agg':
365 if gui == 'agg':
366 gui = None
366 gui = None
367 else:
367 else:
368 # We need to read the backend from the original data structure, *not*
368 # We need to read the backend from the original data structure, *not*
369 # from mpl.rcParams, since a prior invocation of %matplotlib may have
369 # from mpl.rcParams, since a prior invocation of %matplotlib may have
370 # overwritten that.
370 # overwritten that.
371 # WARNING: this assumes matplotlib 1.1 or newer!!
371 # WARNING: this assumes matplotlib 1.1 or newer!!
372 backend = matplotlib.rcParamsOrig['backend']
372 backend = matplotlib.rcParamsOrig['backend']
373 # In this case, we need to find what the appropriate gui selection call
373 # In this case, we need to find what the appropriate gui selection call
374 # should be for IPython, so we can activate inputhook accordingly
374 # should be for IPython, so we can activate inputhook accordingly
375 from IPython.core.pylabtools import backend2gui
375 from IPython.core.pylabtools import backend2gui
376 gui = backend2gui.get(backend, None)
376 gui = backend2gui.get(backend, None)
377
377
378 # If we have already had a gui active, we need it and inline are the
378 # If we have already had a gui active, we need it and inline are the
379 # ones allowed.
379 # ones allowed.
380 if gui_select and gui != gui_select:
380 if gui_select and gui != gui_select:
381 gui = gui_select
381 gui = gui_select
382 backend = backends_[gui]
382 backend = backends_[gui]
383
383
384 # Matplotlib before _matplotlib_manages_backends() can return "inline" for
384 # Matplotlib before _matplotlib_manages_backends() can return "inline" for
385 # no gui event loop rather than the None that IPython >= 8.24.0 expects.
385 # no gui event loop rather than the None that IPython >= 8.24.0 expects.
386 if gui == "inline":
386 if gui == "inline":
387 gui = None
387 gui = None
388
388
389 return gui, backend
389 return gui, backend
390
390
391
391
392 def activate_matplotlib(backend):
392 def activate_matplotlib(backend):
393 """Activate the given backend and set interactive to True."""
393 """Activate the given backend and set interactive to True."""
394
394
395 import matplotlib
395 import matplotlib
396 matplotlib.interactive(True)
396 matplotlib.interactive(True)
397
397
398 # Matplotlib had a bug where even switch_backend could not force
398 # Matplotlib had a bug where even switch_backend could not force
399 # the rcParam to update. This needs to be set *before* the module
399 # the rcParam to update. This needs to be set *before* the module
400 # magic of switch_backend().
400 # magic of switch_backend().
401 matplotlib.rcParams['backend'] = backend
401 matplotlib.rcParams['backend'] = backend
402
402
403 # Due to circular imports, pyplot may be only partially initialised
403 # Due to circular imports, pyplot may be only partially initialised
404 # when this function runs.
404 # when this function runs.
405 # So avoid needing matplotlib attribute-lookup to access pyplot.
405 # So avoid needing matplotlib attribute-lookup to access pyplot.
406 from matplotlib import pyplot as plt
406 from matplotlib import pyplot as plt
407
407
408 plt.switch_backend(backend)
408 plt.switch_backend(backend)
409
409
410 plt.show._needmain = False
410 plt.show._needmain = False
411 # We need to detect at runtime whether show() is called by the user.
411 # We need to detect at runtime whether show() is called by the user.
412 # For this, we wrap it into a decorator which adds a 'called' flag.
412 # For this, we wrap it into a decorator which adds a 'called' flag.
413 plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
413 plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
414
414
415
415
416 def import_pylab(user_ns, import_all=True):
416 def import_pylab(user_ns, import_all=True):
417 """Populate the namespace with pylab-related values.
417 """Populate the namespace with pylab-related values.
418
418
419 Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
419 Imports matplotlib, pylab, numpy, and everything from pylab and numpy.
420
420
421 Also imports a few names from IPython (figsize, display, getfigs)
421 Also imports a few names from IPython (figsize, display, getfigs)
422
422
423 """
423 """
424
424
425 # Import numpy as np/pyplot as plt are conventions we're trying to
425 # Import numpy as np/pyplot as plt are conventions we're trying to
426 # somewhat standardize on. Making them available to users by default
426 # somewhat standardize on. Making them available to users by default
427 # will greatly help this.
427 # will greatly help this.
428 s = ("import numpy\n"
428 s = ("import numpy\n"
429 "import matplotlib\n"
429 "import matplotlib\n"
430 "from matplotlib import pylab, mlab, pyplot\n"
430 "from matplotlib import pylab, mlab, pyplot\n"
431 "np = numpy\n"
431 "np = numpy\n"
432 "plt = pyplot\n"
432 "plt = pyplot\n"
433 )
433 )
434 exec(s, user_ns)
434 exec(s, user_ns)
435
435
436 if import_all:
436 if import_all:
437 s = ("from matplotlib.pylab import *\n"
437 s = ("from matplotlib.pylab import *\n"
438 "from numpy import *\n")
438 "from numpy import *\n")
439 exec(s, user_ns)
439 exec(s, user_ns)
440
440
441 # IPython symbols to add
441 # IPython symbols to add
442 user_ns['figsize'] = figsize
442 user_ns['figsize'] = figsize
443 from IPython.display import display
443 from IPython.display import display
444 # Add display and getfigs to the user's namespace
444 # Add display and getfigs to the user's namespace
445 user_ns['display'] = display
445 user_ns['display'] = display
446 user_ns['getfigs'] = getfigs
446 user_ns['getfigs'] = getfigs
447
447
448
448
449 def configure_inline_support(shell, backend):
449 def configure_inline_support(shell, backend):
450 """
450 """
451 .. deprecated:: 7.23
451 .. deprecated:: 7.23
452
452
453 use `matplotlib_inline.backend_inline.configure_inline_support()`
453 use `matplotlib_inline.backend_inline.configure_inline_support()`
454
454
455 Configure an IPython shell object for matplotlib use.
455 Configure an IPython shell object for matplotlib use.
456
456
457 Parameters
457 Parameters
458 ----------
458 ----------
459 shell : InteractiveShell instance
459 shell : InteractiveShell instance
460 backend : matplotlib backend
460 backend : matplotlib backend
461 """
461 """
462 warnings.warn(
462 warnings.warn(
463 "`configure_inline_support` is deprecated since IPython 7.23, directly "
463 "`configure_inline_support` is deprecated since IPython 7.23, directly "
464 "use `matplotlib_inline.backend_inline.configure_inline_support()`",
464 "use `matplotlib_inline.backend_inline.configure_inline_support()`",
465 DeprecationWarning,
465 DeprecationWarning,
466 stacklevel=2,
466 stacklevel=2,
467 )
467 )
468
468
469 from matplotlib_inline.backend_inline import (
469 from matplotlib_inline.backend_inline import (
470 configure_inline_support as configure_inline_support_orig,
470 configure_inline_support as configure_inline_support_orig,
471 )
471 )
472
472
473 configure_inline_support_orig(shell, backend)
473 configure_inline_support_orig(shell, backend)
474
474
475
475
476 # Determine if Matplotlib manages backends only if needed, and cache result.
476 # Determine if Matplotlib manages backends only if needed, and cache result.
477 # Do not read this directly, instead use _matplotlib_manages_backends().
477 # Do not read this directly, instead use _matplotlib_manages_backends().
478 _matplotlib_manages_backends_value: bool | None = None
478 _matplotlib_manages_backends_value: bool | None = None
479
479
480
480
481 def _matplotlib_manages_backends() -> bool:
481 def _matplotlib_manages_backends() -> bool:
482 """Return True if Matplotlib manages backends, False otherwise.
482 """Return True if Matplotlib manages backends, False otherwise.
483
483
484 If it returns True, the caller can be sure that
484 If it returns True, the caller can be sure that
485 matplotlib.backends.registry.backend_registry is available along with
485 matplotlib.backends.registry.backend_registry is available along with
486 member functions resolve_gui_or_backend, resolve_backend, list_all, and
486 member functions resolve_gui_or_backend, resolve_backend, list_all, and
487 list_gui_frameworks.
487 list_gui_frameworks.
488
489 This function can be removed as it will always return True when Python
490 3.12, the latest version supported by Matplotlib < 3.9, reaches
491 end-of-life in late 2028.
488 """
492 """
489 global _matplotlib_manages_backends_value
493 global _matplotlib_manages_backends_value
490 if _matplotlib_manages_backends_value is None:
494 if _matplotlib_manages_backends_value is None:
491 try:
495 try:
492 from matplotlib.backends.registry import backend_registry
496 from matplotlib.backends.registry import backend_registry
493
497
494 _matplotlib_manages_backends_value = hasattr(
498 _matplotlib_manages_backends_value = hasattr(
495 backend_registry, "resolve_gui_or_backend"
499 backend_registry, "resolve_gui_or_backend"
496 )
500 )
497 except ImportError:
501 except ImportError:
498 _matplotlib_manages_backends_value = False
502 _matplotlib_manages_backends_value = False
499
503
500 return _matplotlib_manages_backends_value
504 return _matplotlib_manages_backends_value
501
505
502
506
503 def _list_matplotlib_backends_and_gui_loops() -> list[str]:
507 def _list_matplotlib_backends_and_gui_loops() -> list[str]:
504 """Return list of all Matplotlib backends and GUI event loops.
508 """Return list of all Matplotlib backends and GUI event loops.
505
509
506 This is the list returned by
510 This is the list returned by
507 %matplotlib --list
511 %matplotlib --list
508 """
512 """
509 if _matplotlib_manages_backends():
513 if _matplotlib_manages_backends():
510 from matplotlib.backends.registry import backend_registry
514 from matplotlib.backends.registry import backend_registry
511
515
512 ret = backend_registry.list_all() + backend_registry.list_gui_frameworks()
516 ret = backend_registry.list_all() + backend_registry.list_gui_frameworks()
513 else:
517 else:
514 from IPython.core import pylabtools
518 from IPython.core import pylabtools
515
519
516 ret = list(pylabtools.backends.keys())
520 ret = list(pylabtools.backends.keys())
517
521
518 return sorted(["auto"] + ret)
522 return sorted(["auto"] + ret)
@@ -1,491 +1,495 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A mixin for :class:`~IPython.core.application.Application` classes that
3 A mixin for :class:`~IPython.core.application.Application` classes that
4 launch InteractiveShell instances, load extensions, etc.
4 launch InteractiveShell instances, load extensions, etc.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 import glob
10 import glob
11 from itertools import chain
11 from itertools import chain
12 import os
12 import os
13 import sys
13 import sys
14 import typing as t
14 import typing as t
15
15
16 from traitlets.config.application import boolean_flag
16 from traitlets.config.application import boolean_flag
17 from traitlets.config.configurable import Configurable
17 from traitlets.config.configurable import Configurable
18 from traitlets.config.loader import Config
18 from traitlets.config.loader import Config
19 from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS
19 from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS
20 from IPython.utils.contexts import preserve_keys
20 from IPython.utils.contexts import preserve_keys
21 from IPython.utils.path import filefind
21 from IPython.utils.path import filefind
22 from traitlets import (
22 from traitlets import (
23 Unicode,
23 Unicode,
24 Instance,
24 Instance,
25 List,
25 List,
26 Bool,
26 Bool,
27 CaselessStrEnum,
27 CaselessStrEnum,
28 observe,
28 observe,
29 DottedObjectName,
29 DottedObjectName,
30 Undefined,
30 Undefined,
31 )
31 )
32 from IPython.terminal import pt_inputhooks
32 from IPython.terminal import pt_inputhooks
33
33
34 # -----------------------------------------------------------------------------
34 # -----------------------------------------------------------------------------
35 # Aliases and Flags
35 # Aliases and Flags
36 # -----------------------------------------------------------------------------
36 # -----------------------------------------------------------------------------
37
37
38 gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
38 gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
39
39
40 shell_flags = {}
40 shell_flags = {}
41
41
42 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
42 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
43 addflag(
43 addflag(
44 "autoindent",
44 "autoindent",
45 "InteractiveShell.autoindent",
45 "InteractiveShell.autoindent",
46 "Turn on autoindenting.",
46 "Turn on autoindenting.",
47 "Turn off autoindenting.",
47 "Turn off autoindenting.",
48 )
48 )
49 addflag(
49 addflag(
50 "automagic",
50 "automagic",
51 "InteractiveShell.automagic",
51 "InteractiveShell.automagic",
52 """Turn on the auto calling of magic commands. Type %%magic at the
52 """Turn on the auto calling of magic commands. Type %%magic at the
53 IPython prompt for more information.""",
53 IPython prompt for more information.""",
54 'Turn off the auto calling of magic commands.'
54 'Turn off the auto calling of magic commands.'
55 )
55 )
56 addflag('pdb', 'InteractiveShell.pdb',
56 addflag('pdb', 'InteractiveShell.pdb',
57 "Enable auto calling the pdb debugger after every exception.",
57 "Enable auto calling the pdb debugger after every exception.",
58 "Disable auto calling the pdb debugger after every exception."
58 "Disable auto calling the pdb debugger after every exception."
59 )
59 )
60 addflag('pprint', 'PlainTextFormatter.pprint',
60 addflag('pprint', 'PlainTextFormatter.pprint',
61 "Enable auto pretty printing of results.",
61 "Enable auto pretty printing of results.",
62 "Disable auto pretty printing of results."
62 "Disable auto pretty printing of results."
63 )
63 )
64 addflag('color-info', 'InteractiveShell.color_info',
64 addflag('color-info', 'InteractiveShell.color_info',
65 """IPython can display information about objects via a set of functions,
65 """IPython can display information about objects via a set of functions,
66 and optionally can use colors for this, syntax highlighting
66 and optionally can use colors for this, syntax highlighting
67 source code and various other elements. This is on by default, but can cause
67 source code and various other elements. This is on by default, but can cause
68 problems with some pagers. If you see such problems, you can disable the
68 problems with some pagers. If you see such problems, you can disable the
69 colours.""",
69 colours.""",
70 "Disable using colors for info related things."
70 "Disable using colors for info related things."
71 )
71 )
72 addflag('ignore-cwd', 'InteractiveShellApp.ignore_cwd',
72 addflag('ignore-cwd', 'InteractiveShellApp.ignore_cwd',
73 "Exclude the current working directory from sys.path",
73 "Exclude the current working directory from sys.path",
74 "Include the current working directory in sys.path",
74 "Include the current working directory in sys.path",
75 )
75 )
76 nosep_config = Config()
76 nosep_config = Config()
77 nosep_config.InteractiveShell.separate_in = ''
77 nosep_config.InteractiveShell.separate_in = ''
78 nosep_config.InteractiveShell.separate_out = ''
78 nosep_config.InteractiveShell.separate_out = ''
79 nosep_config.InteractiveShell.separate_out2 = ''
79 nosep_config.InteractiveShell.separate_out2 = ''
80
80
81 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
81 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
82 shell_flags['pylab'] = (
82 shell_flags['pylab'] = (
83 {'InteractiveShellApp' : {'pylab' : 'auto'}},
83 {'InteractiveShellApp' : {'pylab' : 'auto'}},
84 """Pre-load matplotlib and numpy for interactive use with
84 """Pre-load matplotlib and numpy for interactive use with
85 the default matplotlib backend."""
85 the default matplotlib backend. The exact options available
86 depend on what Matplotlib provides at runtime.""",
86 )
87 )
87 shell_flags['matplotlib'] = (
88 shell_flags['matplotlib'] = (
88 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
89 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
89 """Configure matplotlib for interactive use with
90 """Configure matplotlib for interactive use with
90 the default matplotlib backend."""
91 the default matplotlib backend. The exact options available
92 depend on what Matplotlib provides at runtime.""",
91 )
93 )
92
94
93 # it's possible we don't want short aliases for *all* of these:
95 # it's possible we don't want short aliases for *all* of these:
94 shell_aliases = dict(
96 shell_aliases = dict(
95 autocall='InteractiveShell.autocall',
97 autocall='InteractiveShell.autocall',
96 colors='InteractiveShell.colors',
98 colors='InteractiveShell.colors',
97 logfile='InteractiveShell.logfile',
99 logfile='InteractiveShell.logfile',
98 logappend='InteractiveShell.logappend',
100 logappend='InteractiveShell.logappend',
99 c='InteractiveShellApp.code_to_run',
101 c='InteractiveShellApp.code_to_run',
100 m='InteractiveShellApp.module_to_run',
102 m='InteractiveShellApp.module_to_run',
101 ext="InteractiveShellApp.extra_extensions",
103 ext="InteractiveShellApp.extra_extensions",
102 gui='InteractiveShellApp.gui',
104 gui='InteractiveShellApp.gui',
103 pylab='InteractiveShellApp.pylab',
105 pylab='InteractiveShellApp.pylab',
104 matplotlib='InteractiveShellApp.matplotlib',
106 matplotlib='InteractiveShellApp.matplotlib',
105 )
107 )
106 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
108 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
107
109
108
110
109 # -----------------------------------------------------------------------------
111 # -----------------------------------------------------------------------------
110 # Traitlets
112 # Traitlets
111 # -----------------------------------------------------------------------------
113 # -----------------------------------------------------------------------------
112
114
113
115
114 class MatplotlibBackendCaselessStrEnum(CaselessStrEnum):
116 class MatplotlibBackendCaselessStrEnum(CaselessStrEnum):
115 """An enum of Matplotlib backend strings where the case should be ignored.
117 """An enum of Matplotlib backend strings where the case should be ignored.
116
118
117 Prior to Matplotlib 3.9.1 the list of valid backends is hardcoded in
119 Prior to Matplotlib 3.9.0 the list of valid backends is hardcoded in
118 pylabtools.backends. After that, Matplotlib manages backends.
120 pylabtools.backends. After that, Matplotlib manages backends.
119
121
120 The list of valid backends is determined when it is first needed to avoid
122 The list of valid backends is determined when it is first needed to avoid
121 wasting unnecessary initialisation time.
123 wasting unnecessary initialisation time.
122 """
124 """
123
125
124 def __init__(
126 def __init__(
125 self: CaselessStrEnum[t.Any],
127 self: CaselessStrEnum[t.Any],
126 default_value: t.Any = Undefined,
128 default_value: t.Any = Undefined,
127 **kwargs: t.Any,
129 **kwargs: t.Any,
128 ) -> None:
130 ) -> None:
129 super().__init__(None, default_value=default_value, **kwargs)
131 super().__init__(None, default_value=default_value, **kwargs)
130
132
131 def __getattribute__(self, name):
133 def __getattribute__(self, name):
132 if name == "values" and object.__getattribute__(self, name) is None:
134 if name == "values" and object.__getattribute__(self, name) is None:
133 from IPython.core.pylabtools import _list_matplotlib_backends_and_gui_loops
135 from IPython.core.pylabtools import _list_matplotlib_backends_and_gui_loops
134
136
135 self.values = _list_matplotlib_backends_and_gui_loops()
137 self.values = _list_matplotlib_backends_and_gui_loops()
136 return object.__getattribute__(self, name)
138 return object.__getattribute__(self, name)
137
139
138
140
139 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
140 # Main classes and functions
142 # Main classes and functions
141 #-----------------------------------------------------------------------------
143 #-----------------------------------------------------------------------------
142
144
143 class InteractiveShellApp(Configurable):
145 class InteractiveShellApp(Configurable):
144 """A Mixin for applications that start InteractiveShell instances.
146 """A Mixin for applications that start InteractiveShell instances.
145
147
146 Provides configurables for loading extensions and executing files
148 Provides configurables for loading extensions and executing files
147 as part of configuring a Shell environment.
149 as part of configuring a Shell environment.
148
150
149 The following methods should be called by the :meth:`initialize` method
151 The following methods should be called by the :meth:`initialize` method
150 of the subclass:
152 of the subclass:
151
153
152 - :meth:`init_path`
154 - :meth:`init_path`
153 - :meth:`init_shell` (to be implemented by the subclass)
155 - :meth:`init_shell` (to be implemented by the subclass)
154 - :meth:`init_gui_pylab`
156 - :meth:`init_gui_pylab`
155 - :meth:`init_extensions`
157 - :meth:`init_extensions`
156 - :meth:`init_code`
158 - :meth:`init_code`
157 """
159 """
158 extensions = List(Unicode(),
160 extensions = List(Unicode(),
159 help="A list of dotted module names of IPython extensions to load."
161 help="A list of dotted module names of IPython extensions to load."
160 ).tag(config=True)
162 ).tag(config=True)
161
163
162 extra_extensions = List(
164 extra_extensions = List(
163 DottedObjectName(),
165 DottedObjectName(),
164 help="""
166 help="""
165 Dotted module name(s) of one or more IPython extensions to load.
167 Dotted module name(s) of one or more IPython extensions to load.
166
168
167 For specifying extra extensions to load on the command-line.
169 For specifying extra extensions to load on the command-line.
168
170
169 .. versionadded:: 7.10
171 .. versionadded:: 7.10
170 """,
172 """,
171 ).tag(config=True)
173 ).tag(config=True)
172
174
173 reraise_ipython_extension_failures = Bool(False,
175 reraise_ipython_extension_failures = Bool(False,
174 help="Reraise exceptions encountered loading IPython extensions?",
176 help="Reraise exceptions encountered loading IPython extensions?",
175 ).tag(config=True)
177 ).tag(config=True)
176
178
177 # Extensions that are always loaded (not configurable)
179 # Extensions that are always loaded (not configurable)
178 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
180 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
179
181
180 hide_initial_ns = Bool(True,
182 hide_initial_ns = Bool(True,
181 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
183 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
182 be hidden from tools like %who?"""
184 be hidden from tools like %who?"""
183 ).tag(config=True)
185 ).tag(config=True)
184
186
185 exec_files = List(Unicode(),
187 exec_files = List(Unicode(),
186 help="""List of files to run at IPython startup."""
188 help="""List of files to run at IPython startup."""
187 ).tag(config=True)
189 ).tag(config=True)
188 exec_PYTHONSTARTUP = Bool(True,
190 exec_PYTHONSTARTUP = Bool(True,
189 help="""Run the file referenced by the PYTHONSTARTUP environment
191 help="""Run the file referenced by the PYTHONSTARTUP environment
190 variable at IPython startup."""
192 variable at IPython startup."""
191 ).tag(config=True)
193 ).tag(config=True)
192 file_to_run = Unicode('',
194 file_to_run = Unicode('',
193 help="""A file to be run""").tag(config=True)
195 help="""A file to be run""").tag(config=True)
194
196
195 exec_lines = List(Unicode(),
197 exec_lines = List(Unicode(),
196 help="""lines of code to run at IPython startup."""
198 help="""lines of code to run at IPython startup."""
197 ).tag(config=True)
199 ).tag(config=True)
198 code_to_run = Unicode("", help="Execute the given command string.").tag(config=True)
200 code_to_run = Unicode("", help="Execute the given command string.").tag(config=True)
199 module_to_run = Unicode("", help="Run the module as a script.").tag(config=True)
201 module_to_run = Unicode("", help="Run the module as a script.").tag(config=True)
200 gui = CaselessStrEnum(
202 gui = CaselessStrEnum(
201 gui_keys,
203 gui_keys,
202 allow_none=True,
204 allow_none=True,
203 help="Enable GUI event loop integration with any of {0}.".format(gui_keys),
205 help="Enable GUI event loop integration with any of {0}.".format(gui_keys),
204 ).tag(config=True)
206 ).tag(config=True)
205 matplotlib = MatplotlibBackendCaselessStrEnum(
207 matplotlib = MatplotlibBackendCaselessStrEnum(
206 allow_none=True,
208 allow_none=True,
207 help="""Configure matplotlib for interactive use with
209 help="""Configure matplotlib for interactive use with
208 the default matplotlib backend.""",
210 the default matplotlib backend. The exact options available
211 depend on what Matplotlib provides at runtime.""",
209 ).tag(config=True)
212 ).tag(config=True)
210 pylab = MatplotlibBackendCaselessStrEnum(
213 pylab = MatplotlibBackendCaselessStrEnum(
211 allow_none=True,
214 allow_none=True,
212 help="""Pre-load matplotlib and numpy for interactive use,
215 help="""Pre-load matplotlib and numpy for interactive use,
213 selecting a particular matplotlib backend and loop integration.
216 selecting a particular matplotlib backend and loop integration.
217 The exact options available depend on what Matplotlib provides at runtime.
214 """,
218 """,
215 ).tag(config=True)
219 ).tag(config=True)
216 pylab_import_all = Bool(
220 pylab_import_all = Bool(
217 True,
221 True,
218 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
222 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
219 and an ``import *`` is done from numpy and pylab, when using pylab mode.
223 and an ``import *`` is done from numpy and pylab, when using pylab mode.
220
224
221 When False, pylab mode should not import any names into the user namespace.
225 When False, pylab mode should not import any names into the user namespace.
222 """,
226 """,
223 ).tag(config=True)
227 ).tag(config=True)
224 ignore_cwd = Bool(
228 ignore_cwd = Bool(
225 False,
229 False,
226 help="""If True, IPython will not add the current working directory to sys.path.
230 help="""If True, IPython will not add the current working directory to sys.path.
227 When False, the current working directory is added to sys.path, allowing imports
231 When False, the current working directory is added to sys.path, allowing imports
228 of modules defined in the current directory."""
232 of modules defined in the current directory."""
229 ).tag(config=True)
233 ).tag(config=True)
230 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
234 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
231 allow_none=True)
235 allow_none=True)
232 # whether interact-loop should start
236 # whether interact-loop should start
233 interact = Bool(True)
237 interact = Bool(True)
234
238
235 user_ns = Instance(dict, args=None, allow_none=True)
239 user_ns = Instance(dict, args=None, allow_none=True)
236 @observe('user_ns')
240 @observe('user_ns')
237 def _user_ns_changed(self, change):
241 def _user_ns_changed(self, change):
238 if self.shell is not None:
242 if self.shell is not None:
239 self.shell.user_ns = change['new']
243 self.shell.user_ns = change['new']
240 self.shell.init_user_ns()
244 self.shell.init_user_ns()
241
245
242 def init_path(self):
246 def init_path(self):
243 """Add current working directory, '', to sys.path
247 """Add current working directory, '', to sys.path
244
248
245 Unlike Python's default, we insert before the first `site-packages`
249 Unlike Python's default, we insert before the first `site-packages`
246 or `dist-packages` directory,
250 or `dist-packages` directory,
247 so that it is after the standard library.
251 so that it is after the standard library.
248
252
249 .. versionchanged:: 7.2
253 .. versionchanged:: 7.2
250 Try to insert after the standard library, instead of first.
254 Try to insert after the standard library, instead of first.
251 .. versionchanged:: 8.0
255 .. versionchanged:: 8.0
252 Allow optionally not including the current directory in sys.path
256 Allow optionally not including the current directory in sys.path
253 """
257 """
254 if '' in sys.path or self.ignore_cwd:
258 if '' in sys.path or self.ignore_cwd:
255 return
259 return
256 for idx, path in enumerate(sys.path):
260 for idx, path in enumerate(sys.path):
257 parent, last_part = os.path.split(path)
261 parent, last_part = os.path.split(path)
258 if last_part in {'site-packages', 'dist-packages'}:
262 if last_part in {'site-packages', 'dist-packages'}:
259 break
263 break
260 else:
264 else:
261 # no site-packages or dist-packages found (?!)
265 # no site-packages or dist-packages found (?!)
262 # back to original behavior of inserting at the front
266 # back to original behavior of inserting at the front
263 idx = 0
267 idx = 0
264 sys.path.insert(idx, '')
268 sys.path.insert(idx, '')
265
269
266 def init_shell(self):
270 def init_shell(self):
267 raise NotImplementedError("Override in subclasses")
271 raise NotImplementedError("Override in subclasses")
268
272
269 def init_gui_pylab(self):
273 def init_gui_pylab(self):
270 """Enable GUI event loop integration, taking pylab into account."""
274 """Enable GUI event loop integration, taking pylab into account."""
271 enable = False
275 enable = False
272 shell = self.shell
276 shell = self.shell
273 if self.pylab:
277 if self.pylab:
274 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
278 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
275 key = self.pylab
279 key = self.pylab
276 elif self.matplotlib:
280 elif self.matplotlib:
277 enable = shell.enable_matplotlib
281 enable = shell.enable_matplotlib
278 key = self.matplotlib
282 key = self.matplotlib
279 elif self.gui:
283 elif self.gui:
280 enable = shell.enable_gui
284 enable = shell.enable_gui
281 key = self.gui
285 key = self.gui
282
286
283 if not enable:
287 if not enable:
284 return
288 return
285
289
286 try:
290 try:
287 r = enable(key)
291 r = enable(key)
288 except ImportError:
292 except ImportError:
289 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
293 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
290 self.shell.showtraceback()
294 self.shell.showtraceback()
291 return
295 return
292 except Exception:
296 except Exception:
293 self.log.warning("GUI event loop or pylab initialization failed")
297 self.log.warning("GUI event loop or pylab initialization failed")
294 self.shell.showtraceback()
298 self.shell.showtraceback()
295 return
299 return
296
300
297 if isinstance(r, tuple):
301 if isinstance(r, tuple):
298 gui, backend = r[:2]
302 gui, backend = r[:2]
299 self.log.info("Enabling GUI event loop integration, "
303 self.log.info("Enabling GUI event loop integration, "
300 "eventloop=%s, matplotlib=%s", gui, backend)
304 "eventloop=%s, matplotlib=%s", gui, backend)
301 if key == "auto":
305 if key == "auto":
302 print("Using matplotlib backend: %s" % backend)
306 print("Using matplotlib backend: %s" % backend)
303 else:
307 else:
304 gui = r
308 gui = r
305 self.log.info("Enabling GUI event loop integration, "
309 self.log.info("Enabling GUI event loop integration, "
306 "eventloop=%s", gui)
310 "eventloop=%s", gui)
307
311
308 def init_extensions(self):
312 def init_extensions(self):
309 """Load all IPython extensions in IPythonApp.extensions.
313 """Load all IPython extensions in IPythonApp.extensions.
310
314
311 This uses the :meth:`ExtensionManager.load_extensions` to load all
315 This uses the :meth:`ExtensionManager.load_extensions` to load all
312 the extensions listed in ``self.extensions``.
316 the extensions listed in ``self.extensions``.
313 """
317 """
314 try:
318 try:
315 self.log.debug("Loading IPython extensions...")
319 self.log.debug("Loading IPython extensions...")
316 extensions = (
320 extensions = (
317 self.default_extensions + self.extensions + self.extra_extensions
321 self.default_extensions + self.extensions + self.extra_extensions
318 )
322 )
319 for ext in extensions:
323 for ext in extensions:
320 try:
324 try:
321 self.log.info("Loading IPython extension: %s", ext)
325 self.log.info("Loading IPython extension: %s", ext)
322 self.shell.extension_manager.load_extension(ext)
326 self.shell.extension_manager.load_extension(ext)
323 except:
327 except:
324 if self.reraise_ipython_extension_failures:
328 if self.reraise_ipython_extension_failures:
325 raise
329 raise
326 msg = ("Error in loading extension: {ext}\n"
330 msg = ("Error in loading extension: {ext}\n"
327 "Check your config files in {location}".format(
331 "Check your config files in {location}".format(
328 ext=ext,
332 ext=ext,
329 location=self.profile_dir.location
333 location=self.profile_dir.location
330 ))
334 ))
331 self.log.warning(msg, exc_info=True)
335 self.log.warning(msg, exc_info=True)
332 except:
336 except:
333 if self.reraise_ipython_extension_failures:
337 if self.reraise_ipython_extension_failures:
334 raise
338 raise
335 self.log.warning("Unknown error in loading extensions:", exc_info=True)
339 self.log.warning("Unknown error in loading extensions:", exc_info=True)
336
340
337 def init_code(self):
341 def init_code(self):
338 """run the pre-flight code, specified via exec_lines"""
342 """run the pre-flight code, specified via exec_lines"""
339 self._run_startup_files()
343 self._run_startup_files()
340 self._run_exec_lines()
344 self._run_exec_lines()
341 self._run_exec_files()
345 self._run_exec_files()
342
346
343 # Hide variables defined here from %who etc.
347 # Hide variables defined here from %who etc.
344 if self.hide_initial_ns:
348 if self.hide_initial_ns:
345 self.shell.user_ns_hidden.update(self.shell.user_ns)
349 self.shell.user_ns_hidden.update(self.shell.user_ns)
346
350
347 # command-line execution (ipython -i script.py, ipython -m module)
351 # command-line execution (ipython -i script.py, ipython -m module)
348 # should *not* be excluded from %whos
352 # should *not* be excluded from %whos
349 self._run_cmd_line_code()
353 self._run_cmd_line_code()
350 self._run_module()
354 self._run_module()
351
355
352 # flush output, so itwon't be attached to the first cell
356 # flush output, so itwon't be attached to the first cell
353 sys.stdout.flush()
357 sys.stdout.flush()
354 sys.stderr.flush()
358 sys.stderr.flush()
355 self.shell._sys_modules_keys = set(sys.modules.keys())
359 self.shell._sys_modules_keys = set(sys.modules.keys())
356
360
357 def _run_exec_lines(self):
361 def _run_exec_lines(self):
358 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
362 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
359 if not self.exec_lines:
363 if not self.exec_lines:
360 return
364 return
361 try:
365 try:
362 self.log.debug("Running code from IPythonApp.exec_lines...")
366 self.log.debug("Running code from IPythonApp.exec_lines...")
363 for line in self.exec_lines:
367 for line in self.exec_lines:
364 try:
368 try:
365 self.log.info("Running code in user namespace: %s" %
369 self.log.info("Running code in user namespace: %s" %
366 line)
370 line)
367 self.shell.run_cell(line, store_history=False)
371 self.shell.run_cell(line, store_history=False)
368 except:
372 except:
369 self.log.warning("Error in executing line in user "
373 self.log.warning("Error in executing line in user "
370 "namespace: %s" % line)
374 "namespace: %s" % line)
371 self.shell.showtraceback()
375 self.shell.showtraceback()
372 except:
376 except:
373 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
377 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
374 self.shell.showtraceback()
378 self.shell.showtraceback()
375
379
376 def _exec_file(self, fname, shell_futures=False):
380 def _exec_file(self, fname, shell_futures=False):
377 try:
381 try:
378 full_filename = filefind(fname, [u'.', self.ipython_dir])
382 full_filename = filefind(fname, [u'.', self.ipython_dir])
379 except IOError:
383 except IOError:
380 self.log.warning("File not found: %r"%fname)
384 self.log.warning("File not found: %r"%fname)
381 return
385 return
382 # Make sure that the running script gets a proper sys.argv as if it
386 # Make sure that the running script gets a proper sys.argv as if it
383 # were run from a system shell.
387 # were run from a system shell.
384 save_argv = sys.argv
388 save_argv = sys.argv
385 sys.argv = [full_filename] + self.extra_args[1:]
389 sys.argv = [full_filename] + self.extra_args[1:]
386 try:
390 try:
387 if os.path.isfile(full_filename):
391 if os.path.isfile(full_filename):
388 self.log.info("Running file in user namespace: %s" %
392 self.log.info("Running file in user namespace: %s" %
389 full_filename)
393 full_filename)
390 # Ensure that __file__ is always defined to match Python
394 # Ensure that __file__ is always defined to match Python
391 # behavior.
395 # behavior.
392 with preserve_keys(self.shell.user_ns, '__file__'):
396 with preserve_keys(self.shell.user_ns, '__file__'):
393 self.shell.user_ns['__file__'] = fname
397 self.shell.user_ns['__file__'] = fname
394 if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'):
398 if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'):
395 self.shell.safe_execfile_ipy(full_filename,
399 self.shell.safe_execfile_ipy(full_filename,
396 shell_futures=shell_futures)
400 shell_futures=shell_futures)
397 else:
401 else:
398 # default to python, even without extension
402 # default to python, even without extension
399 self.shell.safe_execfile(full_filename,
403 self.shell.safe_execfile(full_filename,
400 self.shell.user_ns,
404 self.shell.user_ns,
401 shell_futures=shell_futures,
405 shell_futures=shell_futures,
402 raise_exceptions=True)
406 raise_exceptions=True)
403 finally:
407 finally:
404 sys.argv = save_argv
408 sys.argv = save_argv
405
409
406 def _run_startup_files(self):
410 def _run_startup_files(self):
407 """Run files from profile startup directory"""
411 """Run files from profile startup directory"""
408 startup_dirs = [self.profile_dir.startup_dir] + [
412 startup_dirs = [self.profile_dir.startup_dir] + [
409 os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
413 os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
410 ]
414 ]
411 startup_files = []
415 startup_files = []
412
416
413 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
417 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
414 not (self.file_to_run or self.code_to_run or self.module_to_run):
418 not (self.file_to_run or self.code_to_run or self.module_to_run):
415 python_startup = os.environ['PYTHONSTARTUP']
419 python_startup = os.environ['PYTHONSTARTUP']
416 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
420 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
417 try:
421 try:
418 self._exec_file(python_startup)
422 self._exec_file(python_startup)
419 except:
423 except:
420 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
424 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
421 self.shell.showtraceback()
425 self.shell.showtraceback()
422 for startup_dir in startup_dirs[::-1]:
426 for startup_dir in startup_dirs[::-1]:
423 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
427 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
424 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
428 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
425 if not startup_files:
429 if not startup_files:
426 return
430 return
427
431
428 self.log.debug("Running startup files from %s...", startup_dir)
432 self.log.debug("Running startup files from %s...", startup_dir)
429 try:
433 try:
430 for fname in sorted(startup_files):
434 for fname in sorted(startup_files):
431 self._exec_file(fname)
435 self._exec_file(fname)
432 except:
436 except:
433 self.log.warning("Unknown error in handling startup files:")
437 self.log.warning("Unknown error in handling startup files:")
434 self.shell.showtraceback()
438 self.shell.showtraceback()
435
439
436 def _run_exec_files(self):
440 def _run_exec_files(self):
437 """Run files from IPythonApp.exec_files"""
441 """Run files from IPythonApp.exec_files"""
438 if not self.exec_files:
442 if not self.exec_files:
439 return
443 return
440
444
441 self.log.debug("Running files in IPythonApp.exec_files...")
445 self.log.debug("Running files in IPythonApp.exec_files...")
442 try:
446 try:
443 for fname in self.exec_files:
447 for fname in self.exec_files:
444 self._exec_file(fname)
448 self._exec_file(fname)
445 except:
449 except:
446 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
450 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
447 self.shell.showtraceback()
451 self.shell.showtraceback()
448
452
449 def _run_cmd_line_code(self):
453 def _run_cmd_line_code(self):
450 """Run code or file specified at the command-line"""
454 """Run code or file specified at the command-line"""
451 if self.code_to_run:
455 if self.code_to_run:
452 line = self.code_to_run
456 line = self.code_to_run
453 try:
457 try:
454 self.log.info("Running code given at command line (c=): %s" %
458 self.log.info("Running code given at command line (c=): %s" %
455 line)
459 line)
456 self.shell.run_cell(line, store_history=False)
460 self.shell.run_cell(line, store_history=False)
457 except:
461 except:
458 self.log.warning("Error in executing line in user namespace: %s" %
462 self.log.warning("Error in executing line in user namespace: %s" %
459 line)
463 line)
460 self.shell.showtraceback()
464 self.shell.showtraceback()
461 if not self.interact:
465 if not self.interact:
462 self.exit(1)
466 self.exit(1)
463
467
464 # Like Python itself, ignore the second if the first of these is present
468 # Like Python itself, ignore the second if the first of these is present
465 elif self.file_to_run:
469 elif self.file_to_run:
466 fname = self.file_to_run
470 fname = self.file_to_run
467 if os.path.isdir(fname):
471 if os.path.isdir(fname):
468 fname = os.path.join(fname, "__main__.py")
472 fname = os.path.join(fname, "__main__.py")
469 if not os.path.exists(fname):
473 if not os.path.exists(fname):
470 self.log.warning("File '%s' doesn't exist", fname)
474 self.log.warning("File '%s' doesn't exist", fname)
471 if not self.interact:
475 if not self.interact:
472 self.exit(2)
476 self.exit(2)
473 try:
477 try:
474 self._exec_file(fname, shell_futures=True)
478 self._exec_file(fname, shell_futures=True)
475 except:
479 except:
476 self.shell.showtraceback(tb_offset=4)
480 self.shell.showtraceback(tb_offset=4)
477 if not self.interact:
481 if not self.interact:
478 self.exit(1)
482 self.exit(1)
479
483
480 def _run_module(self):
484 def _run_module(self):
481 """Run module specified at the command-line."""
485 """Run module specified at the command-line."""
482 if self.module_to_run:
486 if self.module_to_run:
483 # Make sure that the module gets a proper sys.argv as if it were
487 # Make sure that the module gets a proper sys.argv as if it were
484 # run using `python -m`.
488 # run using `python -m`.
485 save_argv = sys.argv
489 save_argv = sys.argv
486 sys.argv = [sys.executable] + self.extra_args
490 sys.argv = [sys.executable] + self.extra_args
487 try:
491 try:
488 self.shell.safe_run_module(self.module_to_run,
492 self.shell.safe_run_module(self.module_to_run,
489 self.shell.user_ns)
493 self.shell.user_ns)
490 finally:
494 finally:
491 sys.argv = save_argv
495 sys.argv = save_argv
@@ -1,67 +1,81 b''
1 .. _plotting:
1 .. _plotting:
2
2
3 Rich Outputs
3 Rich Outputs
4 ------------
4 ------------
5
5
6 One of the main feature of IPython when used as a kernel is its ability to
6 One of the main feature of IPython when used as a kernel is its ability to
7 show rich output. This means that object that can be representing as image,
7 show rich output. This means that object that can be representing as image,
8 sounds, animation, (etc...) can be shown this way if the frontend support it.
8 sounds, animation, (etc...) can be shown this way if the frontend support it.
9
9
10 In order for this to be possible, you need to use the ``display()`` function,
10 In order for this to be possible, you need to use the ``display()`` function,
11 that should be available by default on IPython 5.4+ and 6.1+, or that you can
11 that should be available by default on IPython 5.4+ and 6.1+, or that you can
12 import with ``from IPython.display import display``. Then use ``display(<your
12 import with ``from IPython.display import display``. Then use ``display(<your
13 object>)`` instead of ``print()``, and if possible your object will be displayed
13 object>)`` instead of ``print()``, and if possible your object will be displayed
14 with a richer representation. In the terminal of course, there won't be much
14 with a richer representation. In the terminal of course, there won't be much
15 difference as object are most of the time represented by text, but in notebook
15 difference as object are most of the time represented by text, but in notebook
16 and similar interface you will get richer outputs.
16 and similar interface you will get richer outputs.
17
17
18
18
19 .. _matplotlib_magic:
20
19 Plotting
21 Plotting
20 --------
22 --------
21
23
22 .. note::
24 .. note::
23
25
24 Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
26 Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
25 IPython's specific magic and use
27 IPython's specific magic and use
26 ``matplotlib.pyplot.ion()``/``matplotlib.pyplot.ioff()`` which have the
28 ``matplotlib.pyplot.ion()``/``matplotlib.pyplot.ioff()`` which have the
27 advantages of working outside of IPython as well.
29 advantages of working outside of IPython as well.
28
30
29
31
30 One major feature of the IPython kernel is the ability to display plots that
32 One major feature of the IPython kernel is the ability to display plots that
31 are the output of running code cells. The IPython kernel is designed to work
33 are the output of running code cells. The IPython kernel is designed to work
32 seamlessly with the matplotlib_ plotting library to provide this functionality.
34 seamlessly with the matplotlib_ plotting library to provide this functionality.
33
35
34 To set this up, before any plotting or import of matplotlib is performed you
36 To set this up, before any plotting or import of matplotlib is performed you
35 must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This
37 may execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This
36 performs the necessary behind-the-scenes setup for IPython to work correctly
38 performs the necessary behind-the-scenes setup for IPython to work correctly
37 hand in hand with ``matplotlib``; it does *not*, however, actually execute any
39 hand in hand with ``matplotlib``; it does *not*, however, actually execute any
38 Python ``import`` commands, that is, no names are added to the namespace.
40 Python ``import`` commands, that is, no names are added to the namespace.
39
41
40 If the ``%matplotlib`` magic is called without an argument, the
42 If you do not use the ``%matplotlib`` magic or you call it without an argument,
41 output of a plotting command is displayed using the default ``matplotlib``
43 the output of a plotting command is displayed using the default ``matplotlib``
42 backend in a separate window. Alternatively, the backend can be explicitly
44 backend, which may be different depending on Operating System and whether
43 requested using, for example::
45 running within Jupyter or not.
46
47 Alternatively, the backend can be explicitly requested using, for example::
44
48
45 %matplotlib gtk
49 %matplotlib gtk
46
50
47 A particularly interesting backend, provided by IPython, is the ``inline``
51 The argument passed to the ``%matplotlib`` magic command may be the name of any
48 backend. This is available only for the Jupyter Notebook and the
52 backend understood by ``matplotlib`` or it may the name of a GUI loop such as
49 Jupyter QtConsole. It can be invoked as follows::
53 ``qt`` or ``osx``, in which case an appropriate backend supporting that GUI
54 loop will be selected. To obtain a full list of all backends and GUI loops
55 understood by ``matplotlib`` use ``%matplotlib --list``.
50
56
51 %matplotlib inline
57 There are some specific backends that are used in the Jupyter ecosystem:
52
58
53 With this backend, the output of plotting commands is displayed *inline* within
59 - The ``inline`` backend is provided by IPython and can be used in Jupyter Lab,
54 frontends like the Jupyter notebook, directly below the code cell that produced
60 Notebook and QtConsole; it is the default backend when using Jupyter. The
55 it. The resulting plots will then also be stored in the notebook document.
61 outputs of plotting commands are displayed *inline* within frontends like
62 Jupyter Notebook, directly below the code cells that produced them.
63 The resulting plots will then also be stored in the notebook document.
56
64
57 .. seealso::
65 - The ``notebook`` or ``nbagg`` backend is built into ``matplotlib`` and can be
66 used with Jupyter ``notebook <7`` and ``nbclassic``. Plots are interactive so
67 they can be zoomed and panned.
58
68
59 `Plotting with Matplotlib`_ example notebook
69 - The ``ipympl`` or ``widget`` backend is for use with Jupyter ``lab`` and
70 ``notebook >=7``. It is in a separate ``ipympl`` module that must be
71 installed using ``pip`` or ``conda`` in the usual manner. Plots are
72 interactive so they can be zoomed and panned.
60
73
74 .. seealso::
61
75
62 The matplotlib_ library also ships with ``%matplotlib notebook`` command that
76 `Plotting with Matplotlib`_ example notebook
63 allows interactive figures if your environment allows it.
64
77
65 See the matplotlib_ documentation for more information.
78 See the matplotlib_ documentation for more information, in particular the
79 section on backends.
66
80
67 .. include:: ../links.txt
81 .. include:: ../links.txt
@@ -1,1037 +1,1017 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 If invoked with no options, it executes the file and exits, passing the
14 If invoked with no options, it executes the file and exits, passing the
15 remaining arguments to the script, just as if you had specified the same
15 remaining arguments to the script, just as if you had specified the same
16 command with python. You may need to specify `--` before args to be passed
16 command with python. You may need to specify `--` before args to be passed
17 to the script, to prevent IPython from attempting to parse them.
17 to the script, to prevent IPython from attempting to parse them.
18 If you add the ``-i`` flag, it drops you into the interpreter while still
18 If you add the ``-i`` flag, it drops you into the interpreter while still
19 acknowledging any options you may have set in your ``ipython_config.py``. This
19 acknowledging any options you may have set in your ``ipython_config.py``. This
20 behavior is different from standard Python, which when called as python ``-i``
20 behavior is different from standard Python, which when called as python ``-i``
21 will only execute one file and ignore your configuration setup.
21 will only execute one file and ignore your configuration setup.
22
22
23 Please note that some of the configuration options are not available at the
23 Please note that some of the configuration options are not available at the
24 command line, simply because they are not practical here. Look into your
24 command line, simply because they are not practical here. Look into your
25 configuration files for details on those. There are separate configuration files
25 configuration files for details on those. There are separate configuration files
26 for each profile, and the files look like :file:`ipython_config.py` or
26 for each profile, and the files look like :file:`ipython_config.py` or
27 :file:`ipython_config_{frontendname}.py`. Profile directories look like
27 :file:`ipython_config_{frontendname}.py`. Profile directories look like
28 :file:`profile_{profilename}` and are typically installed in the
28 :file:`profile_{profilename}` and are typically installed in the
29 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
29 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
30 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
30 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
31 most instances.
31 most instances.
32
32
33 Command-line Options
33 Command-line Options
34 --------------------
34 --------------------
35
35
36 To see the options IPython accepts, use ``ipython --help`` (and you probably
36 To see the options IPython accepts, use ``ipython --help`` (and you probably
37 should run the output through a pager such as ``ipython --help | less`` for
37 should run the output through a pager such as ``ipython --help | less`` for
38 more convenient reading). This shows all the options that have a single-word
38 more convenient reading). This shows all the options that have a single-word
39 alias to control them, but IPython lets you configure all of its objects from
39 alias to control them, but IPython lets you configure all of its objects from
40 the command-line by passing the full class name and a corresponding value; type
40 the command-line by passing the full class name and a corresponding value; type
41 ``ipython --help-all`` to see this full list. For example::
41 ``ipython --help-all`` to see this full list. For example::
42
42
43 $ ipython --help-all
43 $ ipython --help-all
44 <...snip...>
44 <...snip...>
45 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
45 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
46 Default: None
46 Default: None
47 Choices: ['auto', 'gtk', 'gtk3', 'gtk4', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt5', 'qt6', 'tk', 'wx']
47 Choices: ['auto', 'gtk3', 'gtk4', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt5', 'qt6', 'tk', 'wx']
48 Configure matplotlib for interactive use with the default matplotlib
48 Configure matplotlib for interactive use with the default matplotlib
49 backend.
49 backend.
50 <...snip...>
50 <...snip...>
51
51
52
52
53 Indicate that the following::
53 Indicate that the following::
54
54
55 $ ipython --matplotlib qt
55 $ ipython --matplotlib qt
56
56
57
57
58 is equivalent to::
58 is equivalent to::
59
59
60 $ ipython --InteractiveShellApp.matplotlib='qt'
60 $ ipython --InteractiveShellApp.matplotlib='qt'
61
61
62 Note that in the second form, you *must* use the equal sign, as the expression
62 Note that in the second form, you *must* use the equal sign, as the expression
63 is evaluated as an actual Python assignment. While in the above example the
63 is evaluated as an actual Python assignment. While in the above example the
64 short form is more convenient, only the most common options have a short form,
64 short form is more convenient, only the most common options have a short form,
65 while any configurable variable in IPython can be set at the command-line by
65 while any configurable variable in IPython can be set at the command-line by
66 using the long form. This long form is the same syntax used in the
66 using the long form. This long form is the same syntax used in the
67 configuration files, if you want to set these options permanently.
67 configuration files, if you want to set these options permanently.
68
68
69
69
70 Interactive use
70 Interactive use
71 ===============
71 ===============
72
72
73 IPython is meant to work as a drop-in replacement for the standard interactive
73 IPython is meant to work as a drop-in replacement for the standard interactive
74 interpreter. As such, any code which is valid python should execute normally
74 interpreter. As such, any code which is valid python should execute normally
75 under IPython (cases where this is not true should be reported as bugs). It
75 under IPython (cases where this is not true should be reported as bugs). It
76 does, however, offer many features which are not available at a standard python
76 does, however, offer many features which are not available at a standard python
77 prompt. What follows is a list of these.
77 prompt. What follows is a list of these.
78
78
79
79
80 Caution for Windows users
80 Caution for Windows users
81 -------------------------
81 -------------------------
82
82
83 Windows, unfortunately, uses the ``\`` character as a path separator. This is a
83 Windows, unfortunately, uses the ``\`` character as a path separator. This is a
84 terrible choice, because ``\`` also represents the escape character in most
84 terrible choice, because ``\`` also represents the escape character in most
85 modern programming languages, including Python. For this reason, using '/'
85 modern programming languages, including Python. For this reason, using '/'
86 character is recommended if you have problems with ``\``. However, in Windows
86 character is recommended if you have problems with ``\``. However, in Windows
87 commands '/' flags options, so you can not use it for the root directory. This
87 commands '/' flags options, so you can not use it for the root directory. This
88 means that paths beginning at the root must be typed in a contrived manner
88 means that paths beginning at the root must be typed in a contrived manner
89 like: ``%copy \opt/foo/bar.txt \tmp``
89 like: ``%copy \opt/foo/bar.txt \tmp``
90
90
91 .. _magic:
91 .. _magic:
92
92
93 Magic command system
93 Magic command system
94 --------------------
94 --------------------
95
95
96 IPython will treat any line whose first character is a % as a special
96 IPython will treat any line whose first character is a % as a special
97 call to a 'magic' function. These allow you to control the behavior of
97 call to a 'magic' function. These allow you to control the behavior of
98 IPython itself, plus a lot of system-type features. They are all
98 IPython itself, plus a lot of system-type features. They are all
99 prefixed with a % character, but parameters are given without
99 prefixed with a % character, but parameters are given without
100 parentheses or quotes.
100 parentheses or quotes.
101
101
102 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
102 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
103 only the rest of the current line, but all lines below them as well, in the
103 only the rest of the current line, but all lines below them as well, in the
104 current execution block. Cell magics can in fact make arbitrary modifications
104 current execution block. Cell magics can in fact make arbitrary modifications
105 to the input they receive, which need not even be valid Python code at all.
105 to the input they receive, which need not even be valid Python code at all.
106 They receive the whole block as a single string.
106 They receive the whole block as a single string.
107
107
108 As a line magic example, the :magic:`cd` magic works just like the OS command of
108 As a line magic example, the :magic:`cd` magic works just like the OS command of
109 the same name::
109 the same name::
110
110
111 In [8]: %cd
111 In [8]: %cd
112 /home/fperez
112 /home/fperez
113
113
114 The following uses the builtin :magic:`timeit` in cell mode::
114 The following uses the builtin :magic:`timeit` in cell mode::
115
115
116 In [10]: %%timeit x = range(10000)
116 In [10]: %%timeit x = range(10000)
117 ...: min(x)
117 ...: min(x)
118 ...: max(x)
118 ...: max(x)
119 ...:
119 ...:
120 518 Β΅s Β± 4.39 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each)
120 518 Β΅s Β± 4.39 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each)
121
121
122 In this case, ``x = range(10000)`` is called as the line argument, and the
122 In this case, ``x = range(10000)`` is called as the line argument, and the
123 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
123 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
124 :magic:`timeit` magic receives both.
124 :magic:`timeit` magic receives both.
125
125
126 If you have 'automagic' enabled (as it is by default), you don't need to type in
126 If you have 'automagic' enabled (as it is by default), you don't need to type in
127 the single ``%`` explicitly for line magics; IPython will scan its internal
127 the single ``%`` explicitly for line magics; IPython will scan its internal
128 list of magic functions and call one if it exists. With automagic on you can
128 list of magic functions and call one if it exists. With automagic on you can
129 then just type ``cd mydir`` to go to directory 'mydir'::
129 then just type ``cd mydir`` to go to directory 'mydir'::
130
130
131 In [9]: cd mydir
131 In [9]: cd mydir
132 /home/fperez/mydir
132 /home/fperez/mydir
133
133
134 Cell magics *always* require an explicit ``%%`` prefix, automagic
134 Cell magics *always* require an explicit ``%%`` prefix, automagic
135 calling only works for line magics.
135 calling only works for line magics.
136
136
137 The automagic system has the lowest possible precedence in name searches, so
137 The automagic system has the lowest possible precedence in name searches, so
138 you can freely use variables with the same names as magic commands. If a magic
138 you can freely use variables with the same names as magic commands. If a magic
139 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
139 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
140 use it:
140 use it:
141
141
142 .. sourcecode:: ipython
142 .. sourcecode:: ipython
143
143
144 In [1]: cd ipython # %cd is called by automagic
144 In [1]: cd ipython # %cd is called by automagic
145 /home/fperez/ipython
145 /home/fperez/ipython
146
146
147 In [2]: cd=1 # now cd is just a variable
147 In [2]: cd=1 # now cd is just a variable
148
148
149 In [3]: cd .. # and doesn't work as a function anymore
149 In [3]: cd .. # and doesn't work as a function anymore
150 File "<ipython-input-3-9fedb3aff56c>", line 1
150 File "<ipython-input-3-9fedb3aff56c>", line 1
151 cd ..
151 cd ..
152 ^
152 ^
153 SyntaxError: invalid syntax
153 SyntaxError: invalid syntax
154
154
155
155
156 In [4]: %cd .. # but %cd always works
156 In [4]: %cd .. # but %cd always works
157 /home/fperez
157 /home/fperez
158
158
159 In [5]: del cd # if you remove the cd variable, automagic works again
159 In [5]: del cd # if you remove the cd variable, automagic works again
160
160
161 In [6]: cd ipython
161 In [6]: cd ipython
162
162
163 /home/fperez/ipython
163 /home/fperez/ipython
164
164
165 Line magics, if they return a value, can be assigned to a variable using the
165 Line magics, if they return a value, can be assigned to a variable using the
166 syntax ``l = %sx ls`` (which in this particular case returns the result of `ls`
166 syntax ``l = %sx ls`` (which in this particular case returns the result of `ls`
167 as a python list). See :ref:`below <manual_capture>` for more information.
167 as a python list). See :ref:`below <manual_capture>` for more information.
168
168
169 Type ``%magic`` for more information, including a list of all available magic
169 Type ``%magic`` for more information, including a list of all available magic
170 functions at any time and their docstrings. You can also type
170 functions at any time and their docstrings. You can also type
171 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
171 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
172 information on the '?' system) to get information about any particular magic
172 information on the '?' system) to get information about any particular magic
173 function you are interested in.
173 function you are interested in.
174
174
175 The API documentation for the :mod:`IPython.core.magic` module contains the full
175 The API documentation for the :mod:`IPython.core.magic` module contains the full
176 docstrings of all currently available magic commands.
176 docstrings of all currently available magic commands.
177
177
178 .. seealso::
178 .. seealso::
179
179
180 :doc:`magics`
180 :doc:`magics`
181 A list of the line and cell magics available in IPython by default
181 A list of the line and cell magics available in IPython by default
182
182
183 :ref:`defining_magics`
183 :ref:`defining_magics`
184 How to define and register additional magic functions
184 How to define and register additional magic functions
185
185
186
186
187 Access to the standard Python help
187 Access to the standard Python help
188 ----------------------------------
188 ----------------------------------
189
189
190 Simply type ``help()`` to access Python's standard help system. You can
190 Simply type ``help()`` to access Python's standard help system. You can
191 also type ``help(object)`` for information about a given object, or
191 also type ``help(object)`` for information about a given object, or
192 ``help('keyword')`` for information on a keyword. You may need to configure your
192 ``help('keyword')`` for information on a keyword. You may need to configure your
193 PYTHONDOCS environment variable for this feature to work correctly.
193 PYTHONDOCS environment variable for this feature to work correctly.
194
194
195 .. _dynamic_object_info:
195 .. _dynamic_object_info:
196
196
197 Dynamic object information
197 Dynamic object information
198 --------------------------
198 --------------------------
199
199
200 Typing ``?word`` or ``word?`` prints detailed information about an object. If
200 Typing ``?word`` or ``word?`` prints detailed information about an object. If
201 certain strings in the object are too long (e.g. function signatures) they get
201 certain strings in the object are too long (e.g. function signatures) they get
202 snipped in the center for brevity. This system gives access variable types and
202 snipped in the center for brevity. This system gives access variable types and
203 values, docstrings, function prototypes and other useful information.
203 values, docstrings, function prototypes and other useful information.
204
204
205 If the information will not fit in the terminal, it is displayed in a pager
205 If the information will not fit in the terminal, it is displayed in a pager
206 (``less`` if available, otherwise a basic internal pager).
206 (``less`` if available, otherwise a basic internal pager).
207
207
208 Typing ``??word`` or ``word??`` gives access to the full information, including
208 Typing ``??word`` or ``word??`` gives access to the full information, including
209 the source code where possible. Long strings are not snipped.
209 the source code where possible. Long strings are not snipped.
210
210
211 The following magic functions are particularly useful for gathering
211 The following magic functions are particularly useful for gathering
212 information about your working environment:
212 information about your working environment:
213
213
214 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
214 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
215 docstring for an object. If the given object is a class, it will
215 docstring for an object. If the given object is a class, it will
216 print both the class and the constructor docstrings.
216 print both the class and the constructor docstrings.
217 * :magic:`pdef` **<object>**: Print the call signature for any callable
217 * :magic:`pdef` **<object>**: Print the call signature for any callable
218 object. If the object is a class, print the constructor information.
218 object. If the object is a class, print the constructor information.
219 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
219 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
220 the source code for an object.
220 the source code for an object.
221 * :magic:`pfile` **<object>**: Show the entire source file where an object was
221 * :magic:`pfile` **<object>**: Show the entire source file where an object was
222 defined via a pager, opening it at the line where the object
222 defined via a pager, opening it at the line where the object
223 definition begins.
223 definition begins.
224 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
224 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
225 you have defined interactively (not things you loaded or defined
225 you have defined interactively (not things you loaded or defined
226 in your configuration files). %who just prints a list of
226 in your configuration files). %who just prints a list of
227 identifiers and %whos prints a table with some basic details about
227 identifiers and %whos prints a table with some basic details about
228 each identifier.
228 each identifier.
229
229
230 The dynamic object information functions (?/??, ``%pdoc``,
230 The dynamic object information functions (?/??, ``%pdoc``,
231 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
231 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
232 directly on variables. For example, after doing ``import os``, you can use
232 directly on variables. For example, after doing ``import os``, you can use
233 ``os.path.abspath??``.
233 ``os.path.abspath??``.
234
234
235
235
236 Command line completion
236 Command line completion
237 +++++++++++++++++++++++
237 +++++++++++++++++++++++
238
238
239 At any time, hitting TAB will complete any available python commands or
239 At any time, hitting TAB will complete any available python commands or
240 variable names, and show you a list of the possible completions if
240 variable names, and show you a list of the possible completions if
241 there's no unambiguous one. It will also complete filenames in the
241 there's no unambiguous one. It will also complete filenames in the
242 current directory if no python names match what you've typed so far.
242 current directory if no python names match what you've typed so far.
243
243
244
244
245 Search command history
245 Search command history
246 ++++++++++++++++++++++
246 ++++++++++++++++++++++
247
247
248 IPython provides two ways for searching through previous input and thus
248 IPython provides two ways for searching through previous input and thus
249 reduce the need for repetitive typing:
249 reduce the need for repetitive typing:
250
250
251 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
251 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
252 and :kbd:`Ctrl-n`) to search through only the history items that match
252 and :kbd:`Ctrl-n`) to search through only the history items that match
253 what you've typed so far.
253 what you've typed so far.
254 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
254 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
255 searches your history for lines that contain what you've typed so
255 searches your history for lines that contain what you've typed so
256 far, completing as much as it can.
256 far, completing as much as it can.
257
257
258 IPython will save your input history when it leaves and reload it next
258 IPython will save your input history when it leaves and reload it next
259 time you restart it. By default, the history file is named
259 time you restart it. By default, the history file is named
260 :file:`.ipython/profile_{name}/history.sqlite`.
260 :file:`.ipython/profile_{name}/history.sqlite`.
261
261
262 Autoindent
262 Autoindent
263 ++++++++++
263 ++++++++++
264
264
265 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
265 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
266 it thus can recognize lines ending in ':' and indent the next line,
266 it thus can recognize lines ending in ':' and indent the next line,
267 while also un-indenting automatically after 'raise' or 'return',
267 while also un-indenting automatically after 'raise' or 'return',
268 and support real multi-line editing as well as syntactic coloration
268 and support real multi-line editing as well as syntactic coloration
269 during edition.
269 during edition.
270
270
271 This feature does not use the ``readline`` library anymore, so it will
271 This feature does not use the ``readline`` library anymore, so it will
272 not honor your :file:`~/.inputrc` configuration (or whatever
272 not honor your :file:`~/.inputrc` configuration (or whatever
273 file your :envvar:`INPUTRC` environment variable points to).
273 file your :envvar:`INPUTRC` environment variable points to).
274
274
275 In particular if you want to change the input mode to ``vi``, you will need to
275 In particular if you want to change the input mode to ``vi``, you will need to
276 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
276 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
277
277
278 Session logging and restoring
278 Session logging and restoring
279 -----------------------------
279 -----------------------------
280
280
281 You can log all input from a session either by starting IPython with the
281 You can log all input from a session either by starting IPython with the
282 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
282 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
283 or by activating the logging at any moment with the magic function :magic:`logstart`.
283 or by activating the logging at any moment with the magic function :magic:`logstart`.
284
284
285 Log files can later be reloaded by running them as scripts and IPython
285 Log files can later be reloaded by running them as scripts and IPython
286 will attempt to 'replay' the log by executing all the lines in it, thus
286 will attempt to 'replay' the log by executing all the lines in it, thus
287 restoring the state of a previous session. This feature is not quite
287 restoring the state of a previous session. This feature is not quite
288 perfect, but can still be useful in many cases.
288 perfect, but can still be useful in many cases.
289
289
290 The log files can also be used as a way to have a permanent record of
290 The log files can also be used as a way to have a permanent record of
291 any code you wrote while experimenting. Log files are regular text files
291 any code you wrote while experimenting. Log files are regular text files
292 which you can later open in your favorite text editor to extract code or
292 which you can later open in your favorite text editor to extract code or
293 to 'clean them up' before using them to replay a session.
293 to 'clean them up' before using them to replay a session.
294
294
295 The :magic:`logstart` function for activating logging in mid-session is used as
295 The :magic:`logstart` function for activating logging in mid-session is used as
296 follows::
296 follows::
297
297
298 %logstart [log_name [log_mode]]
298 %logstart [log_name [log_mode]]
299
299
300 If no name is given, it defaults to a file named 'ipython_log.py' in your
300 If no name is given, it defaults to a file named 'ipython_log.py' in your
301 current working directory, in 'rotate' mode (see below).
301 current working directory, in 'rotate' mode (see below).
302
302
303 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
303 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
304 history up to that point and then continues logging.
304 history up to that point and then continues logging.
305
305
306 %logstart takes a second optional parameter: logging mode. This can be
306 %logstart takes a second optional parameter: logging mode. This can be
307 one of (note that the modes are given unquoted):
307 one of (note that the modes are given unquoted):
308
308
309 * [over:] overwrite existing log_name.
309 * [over:] overwrite existing log_name.
310 * [backup:] rename (if exists) to log_name~ and start log_name.
310 * [backup:] rename (if exists) to log_name~ and start log_name.
311 * [append:] well, that says it.
311 * [append:] well, that says it.
312 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
312 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
313
313
314 Adding the '-o' flag to '%logstart' magic (as in '%logstart -o [log_name [log_mode]]')
314 Adding the '-o' flag to '%logstart' magic (as in '%logstart -o [log_name [log_mode]]')
315 will also include output from iPython in the log file.
315 will also include output from iPython in the log file.
316
316
317 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
317 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
318 resume logging to a file which had previously been started with
318 resume logging to a file which had previously been started with
319 %logstart. They will fail (with an explanation) if you try to use them
319 %logstart. They will fail (with an explanation) if you try to use them
320 before logging has been started.
320 before logging has been started.
321
321
322 .. _system_shell_access:
322 .. _system_shell_access:
323
323
324 System shell access
324 System shell access
325 -------------------
325 -------------------
326
326
327 Any input line beginning with a ``!`` character is passed verbatim (minus
327 Any input line beginning with a ``!`` character is passed verbatim (minus
328 the ``!``, of course) to the underlying operating system. For example,
328 the ``!``, of course) to the underlying operating system. For example,
329 typing ``!ls`` will run 'ls' in the current directory.
329 typing ``!ls`` will run 'ls' in the current directory.
330
330
331 .. _manual_capture:
331 .. _manual_capture:
332
332
333 Manual capture of command output and magic output
333 Manual capture of command output and magic output
334 -------------------------------------------------
334 -------------------------------------------------
335
335
336 You can assign the result of a system command to a Python variable with the
336 You can assign the result of a system command to a Python variable with the
337 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
337 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
338 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
338 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
339 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
339 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
340 and captures the output). Each of these gets machine
340 and captures the output). Each of these gets machine
341 readable output from stdout (e.g. without colours), and splits on newlines. To
341 readable output from stdout (e.g. without colours), and splits on newlines. To
342 explicitly get this sort of output without assigning to a variable, use two
342 explicitly get this sort of output without assigning to a variable, use two
343 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
343 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
344 (However, ``!!`` commands cannot be assigned to a variable.)
344 (However, ``!!`` commands cannot be assigned to a variable.)
345
345
346 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
346 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
347 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
347 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
348 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
348 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
349 See :ref:`string_lists` for details.
349 See :ref:`string_lists` for details.
350
350
351 IPython also allows you to expand the value of python variables when
351 IPython also allows you to expand the value of python variables when
352 making system calls. Wrap variables or expressions in {braces}::
352 making system calls. Wrap variables or expressions in {braces}::
353
353
354 In [1]: pyvar = 'Hello world'
354 In [1]: pyvar = 'Hello world'
355 In [2]: !echo "A python variable: {pyvar}"
355 In [2]: !echo "A python variable: {pyvar}"
356 A python variable: Hello world
356 A python variable: Hello world
357 In [3]: import math
357 In [3]: import math
358 In [4]: x = 8
358 In [4]: x = 8
359 In [5]: !echo {math.factorial(x)}
359 In [5]: !echo {math.factorial(x)}
360 40320
360 40320
361
361
362 For simple cases, you can alternatively prepend $ to a variable name::
362 For simple cases, you can alternatively prepend $ to a variable name::
363
363
364 In [6]: !echo $sys.argv
364 In [6]: !echo $sys.argv
365 [/home/fperez/usr/bin/ipython]
365 [/home/fperez/usr/bin/ipython]
366 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
366 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
367 A system variable: /home/fperez
367 A system variable: /home/fperez
368
368
369 Note that `$$` is used to represent a literal `$`.
369 Note that `$$` is used to represent a literal `$`.
370
370
371 System command aliases
371 System command aliases
372 ----------------------
372 ----------------------
373
373
374 The :magic:`alias` magic function allows you to define magic functions which are in fact
374 The :magic:`alias` magic function allows you to define magic functions which are in fact
375 system shell commands. These aliases can have parameters.
375 system shell commands. These aliases can have parameters.
376
376
377 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
377 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
378
378
379 Then, typing ``alias_name params`` will execute the system command 'cmd
379 Then, typing ``alias_name params`` will execute the system command 'cmd
380 params' (from your underlying operating system).
380 params' (from your underlying operating system).
381
381
382 You can also define aliases with parameters using ``%s`` specifiers (one per
382 You can also define aliases with parameters using ``%s`` specifiers (one per
383 parameter). The following example defines the parts function as an
383 parameter). The following example defines the parts function as an
384 alias to the command ``echo first %s second %s`` where each ``%s`` will be
384 alias to the command ``echo first %s second %s`` where each ``%s`` will be
385 replaced by a positional parameter to the call to %parts::
385 replaced by a positional parameter to the call to %parts::
386
386
387 In [1]: %alias parts echo first %s second %s
387 In [1]: %alias parts echo first %s second %s
388 In [2]: parts A B
388 In [2]: parts A B
389 first A second B
389 first A second B
390 In [3]: parts A
390 In [3]: parts A
391 ERROR: Alias <parts> requires 2 arguments, 1 given.
391 ERROR: Alias <parts> requires 2 arguments, 1 given.
392
392
393 If called with no parameters, :magic:`alias` prints the table of currently
393 If called with no parameters, :magic:`alias` prints the table of currently
394 defined aliases.
394 defined aliases.
395
395
396 The :magic:`rehashx` magic allows you to load your entire $PATH as
396 The :magic:`rehashx` magic allows you to load your entire $PATH as
397 ipython aliases. See its docstring for further details.
397 ipython aliases. See its docstring for further details.
398
398
399
399
400 .. _dreload:
400 .. _dreload:
401
401
402 Recursive reload
402 Recursive reload
403 ----------------
403 ----------------
404
404
405 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
405 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
406 module: changes made to any of its dependencies will be reloaded without
406 module: changes made to any of its dependencies will be reloaded without
407 having to exit. To start using it, do::
407 having to exit. To start using it, do::
408
408
409 from IPython.lib.deepreload import reload as dreload
409 from IPython.lib.deepreload import reload as dreload
410
410
411
411
412 Verbose and colored exception traceback printouts
412 Verbose and colored exception traceback printouts
413 -------------------------------------------------
413 -------------------------------------------------
414
414
415 IPython provides the option to see very detailed exception tracebacks,
415 IPython provides the option to see very detailed exception tracebacks,
416 which can be especially useful when debugging large programs. You can
416 which can be especially useful when debugging large programs. You can
417 run any Python file with the %run function to benefit from these
417 run any Python file with the %run function to benefit from these
418 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
418 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
419 be colored (if your terminal supports it) which makes them much easier
419 be colored (if your terminal supports it) which makes them much easier
420 to parse visually.
420 to parse visually.
421
421
422 See the magic :magic:`xmode` and :magic:`colors` functions for details.
422 See the magic :magic:`xmode` and :magic:`colors` functions for details.
423
423
424 These features are basically a terminal version of Ka-Ping Yee's cgitb
424 These features are basically a terminal version of Ka-Ping Yee's cgitb
425 module, now part of the standard Python library.
425 module, now part of the standard Python library.
426
426
427
427
428 .. _input_caching:
428 .. _input_caching:
429
429
430 Input caching system
430 Input caching system
431 --------------------
431 --------------------
432
432
433 IPython offers numbered prompts (In/Out) with input and output caching
433 IPython offers numbered prompts (In/Out) with input and output caching
434 (also referred to as 'input history'). All input is saved and can be
434 (also referred to as 'input history'). All input is saved and can be
435 retrieved as variables (besides the usual arrow key recall), in
435 retrieved as variables (besides the usual arrow key recall), in
436 addition to the :magic:`rep` magic command that brings a history entry
436 addition to the :magic:`rep` magic command that brings a history entry
437 up for editing on the next command line.
437 up for editing on the next command line.
438
438
439 The following variables always exist:
439 The following variables always exist:
440
440
441 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
441 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
442 previous inputs.
442 previous inputs.
443
443
444 * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line
444 * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line
445 ``n``. If you overwrite In with a variable of your own, you can remake the
445 ``n``. If you overwrite In with a variable of your own, you can remake the
446 assignment to the internal list with a simple ``In=_ih``.
446 assignment to the internal list with a simple ``In=_ih``.
447
447
448 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
448 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
449 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
449 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
450
450
451 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
451 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
452 and ``In[14]``.
452 and ``In[14]``.
453
453
454 This allows you to easily cut and paste multi line interactive prompts
454 This allows you to easily cut and paste multi line interactive prompts
455 by printing them out: they print like a clean string, without prompt
455 by printing them out: they print like a clean string, without prompt
456 characters. You can also manipulate them like regular variables (they
456 characters. You can also manipulate them like regular variables (they
457 are strings), modify or exec them.
457 are strings), modify or exec them.
458
458
459 You can also re-execute multiple lines of input easily by using the magic
459 You can also re-execute multiple lines of input easily by using the magic
460 :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to
460 :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to
461 re-execute previous lines which include magic function calls (which require
461 re-execute previous lines which include magic function calls (which require
462 special processing). Type %macro? for more details on the macro system.
462 special processing). Type %macro? for more details on the macro system.
463
463
464 A history function :magic:`history` allows you to see any part of your input
464 A history function :magic:`history` allows you to see any part of your input
465 history by printing a range of the _i variables.
465 history by printing a range of the _i variables.
466
466
467 You can also search ('grep') through your history by typing
467 You can also search ('grep') through your history by typing
468 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
468 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
469 etc. You can bring history entries listed by '%hist -g' up for editing
469 etc. You can bring history entries listed by '%hist -g' up for editing
470 with the %recall command, or run them immediately with :magic:`rerun`.
470 with the %recall command, or run them immediately with :magic:`rerun`.
471
471
472 .. _output_caching:
472 .. _output_caching:
473
473
474 Output caching system
474 Output caching system
475 ---------------------
475 ---------------------
476
476
477 For output that is returned from actions, a system similar to the input
477 For output that is returned from actions, a system similar to the input
478 cache exists but using _ instead of _i. Only actions that produce a
478 cache exists but using _ instead of _i. Only actions that produce a
479 result (NOT assignments, for example) are cached. If you are familiar
479 result (NOT assignments, for example) are cached. If you are familiar
480 with Mathematica, IPython's _ variables behave exactly like
480 with Mathematica, IPython's _ variables behave exactly like
481 Mathematica's % variables.
481 Mathematica's % variables.
482
482
483 The following variables always exist:
483 The following variables always exist:
484
484
485 * [_] (a single underscore): stores previous output, like Python's
485 * [_] (a single underscore): stores previous output, like Python's
486 default interpreter.
486 default interpreter.
487 * [__] (two underscores): next previous.
487 * [__] (two underscores): next previous.
488 * [___] (three underscores): next-next previous.
488 * [___] (three underscores): next-next previous.
489
489
490 Additionally, global variables named _<n> are dynamically created (<n>
490 Additionally, global variables named _<n> are dynamically created (<n>
491 being the prompt counter), such that the result of output <n> is always
491 being the prompt counter), such that the result of output <n> is always
492 available as _<n> (don't use the angle brackets, just the number, e.g.
492 available as _<n> (don't use the angle brackets, just the number, e.g.
493 ``_21``).
493 ``_21``).
494
494
495 These variables are also stored in a global dictionary (not a
495 These variables are also stored in a global dictionary (not a
496 list, since it only has entries for lines which returned a result)
496 list, since it only has entries for lines which returned a result)
497 available under the names _oh and Out (similar to _ih and In). So the
497 available under the names _oh and Out (similar to _ih and In). So the
498 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
498 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
499 accidentally overwrite the Out variable you can recover it by typing
499 accidentally overwrite the Out variable you can recover it by typing
500 ``Out=_oh`` at the prompt.
500 ``Out=_oh`` at the prompt.
501
501
502 This system obviously can potentially put heavy memory demands on your
502 This system obviously can potentially put heavy memory demands on your
503 system, since it prevents Python's garbage collector from removing any
503 system, since it prevents Python's garbage collector from removing any
504 previously computed results. You can control how many results are kept
504 previously computed results. You can control how many results are kept
505 in memory with the configuration option ``InteractiveShell.cache_size``.
505 in memory with the configuration option ``InteractiveShell.cache_size``.
506 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
506 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
507 and :magic:`xdel` magics to clear large items from memory.
507 and :magic:`xdel` magics to clear large items from memory.
508
508
509 Directory history
509 Directory history
510 -----------------
510 -----------------
511
511
512 Your history of visited directories is kept in the global list _dh, and
512 Your history of visited directories is kept in the global list _dh, and
513 the magic :magic:`cd` command can be used to go to any entry in that list. The
513 the magic :magic:`cd` command can be used to go to any entry in that list. The
514 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
514 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
515 conveniently view the directory history.
515 conveniently view the directory history.
516
516
517
517
518 Automatic parentheses and quotes
518 Automatic parentheses and quotes
519 --------------------------------
519 --------------------------------
520
520
521 These features were adapted from Nathan Gray's LazyPython. They are
521 These features were adapted from Nathan Gray's LazyPython. They are
522 meant to allow less typing for common situations.
522 meant to allow less typing for common situations.
523
523
524 Callable objects (i.e. functions, methods, etc) can be invoked like this
524 Callable objects (i.e. functions, methods, etc) can be invoked like this
525 (notice the commas between the arguments)::
525 (notice the commas between the arguments)::
526
526
527 In [1]: callable_ob arg1, arg2, arg3
527 In [1]: callable_ob arg1, arg2, arg3
528 ------> callable_ob(arg1, arg2, arg3)
528 ------> callable_ob(arg1, arg2, arg3)
529
529
530 .. note::
530 .. note::
531 This feature is disabled by default. To enable it, use the ``%autocall``
531 This feature is disabled by default. To enable it, use the ``%autocall``
532 magic command. The commands below with special prefixes will always work,
532 magic command. The commands below with special prefixes will always work,
533 however.
533 however.
534
534
535 You can force automatic parentheses by using '/' as the first character
535 You can force automatic parentheses by using '/' as the first character
536 of a line. For example::
536 of a line. For example::
537
537
538 In [2]: /globals # becomes 'globals()'
538 In [2]: /globals # becomes 'globals()'
539
539
540 Note that the '/' MUST be the first character on the line! This won't work::
540 Note that the '/' MUST be the first character on the line! This won't work::
541
541
542 In [3]: print /globals # syntax error
542 In [3]: print /globals # syntax error
543
543
544 In most cases the automatic algorithm should work, so you should rarely
544 In most cases the automatic algorithm should work, so you should rarely
545 need to explicitly invoke /. One notable exception is if you are trying
545 need to explicitly invoke /. One notable exception is if you are trying
546 to call a function with a list of tuples as arguments (the parenthesis
546 to call a function with a list of tuples as arguments (the parenthesis
547 will confuse IPython)::
547 will confuse IPython)::
548
548
549 In [4]: zip (1,2,3),(4,5,6) # won't work
549 In [4]: zip (1,2,3),(4,5,6) # won't work
550
550
551 but this will work::
551 but this will work::
552
552
553 In [5]: /zip (1,2,3),(4,5,6)
553 In [5]: /zip (1,2,3),(4,5,6)
554 ------> zip ((1,2,3),(4,5,6))
554 ------> zip ((1,2,3),(4,5,6))
555 Out[5]: [(1, 4), (2, 5), (3, 6)]
555 Out[5]: [(1, 4), (2, 5), (3, 6)]
556
556
557 IPython tells you that it has altered your command line by displaying
557 IPython tells you that it has altered your command line by displaying
558 the new command line preceded by ``--->``.
558 the new command line preceded by ``--->``.
559
559
560 You can force automatic quoting of a function's arguments by using ``,``
560 You can force automatic quoting of a function's arguments by using ``,``
561 or ``;`` as the first character of a line. For example::
561 or ``;`` as the first character of a line. For example::
562
562
563 In [1]: ,my_function /home/me # becomes my_function("/home/me")
563 In [1]: ,my_function /home/me # becomes my_function("/home/me")
564
564
565 If you use ';' the whole argument is quoted as a single string, while ',' splits
565 If you use ';' the whole argument is quoted as a single string, while ',' splits
566 on whitespace::
566 on whitespace::
567
567
568 In [2]: ,my_function a b c # becomes my_function("a","b","c")
568 In [2]: ,my_function a b c # becomes my_function("a","b","c")
569
569
570 In [3]: ;my_function a b c # becomes my_function("a b c")
570 In [3]: ;my_function a b c # becomes my_function("a b c")
571
571
572 Note that the ',' or ';' MUST be the first character on the line! This
572 Note that the ',' or ';' MUST be the first character on the line! This
573 won't work::
573 won't work::
574
574
575 In [4]: x = ,my_function /home/me # syntax error
575 In [4]: x = ,my_function /home/me # syntax error
576
576
577 IPython as your default Python environment
577 IPython as your default Python environment
578 ==========================================
578 ==========================================
579
579
580 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
580 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
581 execute at startup the file referenced by this variable. If you put the
581 execute at startup the file referenced by this variable. If you put the
582 following code at the end of that file, then IPython will be your working
582 following code at the end of that file, then IPython will be your working
583 environment anytime you start Python::
583 environment anytime you start Python::
584
584
585 import os, IPython
585 import os, IPython
586 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
586 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
587 IPython.start_ipython()
587 IPython.start_ipython()
588 raise SystemExit
588 raise SystemExit
589
589
590 The ``raise SystemExit`` is needed to exit Python when
590 The ``raise SystemExit`` is needed to exit Python when
591 it finishes, otherwise you'll be back at the normal Python ``>>>``
591 it finishes, otherwise you'll be back at the normal Python ``>>>``
592 prompt.
592 prompt.
593
593
594 This is probably useful to developers who manage multiple Python
594 This is probably useful to developers who manage multiple Python
595 versions and don't want to have correspondingly multiple IPython
595 versions and don't want to have correspondingly multiple IPython
596 versions. Note that in this mode, there is no way to pass IPython any
596 versions. Note that in this mode, there is no way to pass IPython any
597 command-line options, as those are trapped first by Python itself.
597 command-line options, as those are trapped first by Python itself.
598
598
599 .. _Embedding:
599 .. _Embedding:
600
600
601 Embedding IPython
601 Embedding IPython
602 =================
602 =================
603
603
604 You can start a regular IPython session with
604 You can start a regular IPython session with
605
605
606 .. sourcecode:: python
606 .. sourcecode:: python
607
607
608 import IPython
608 import IPython
609 IPython.start_ipython(argv=[])
609 IPython.start_ipython(argv=[])
610
610
611 at any point in your program. This will load IPython configuration,
611 at any point in your program. This will load IPython configuration,
612 startup files, and everything, just as if it were a normal IPython session.
612 startup files, and everything, just as if it were a normal IPython session.
613 For information on setting configuration options when running IPython from
613 For information on setting configuration options when running IPython from
614 python, see :ref:`configure_start_ipython`.
614 python, see :ref:`configure_start_ipython`.
615
615
616 It is also possible to embed an IPython shell in a namespace in your Python
616 It is also possible to embed an IPython shell in a namespace in your Python
617 code. This allows you to evaluate dynamically the state of your code, operate
617 code. This allows you to evaluate dynamically the state of your code, operate
618 with your variables, analyze them, etc. For example, if you run the following
618 with your variables, analyze them, etc. For example, if you run the following
619 code snippet::
619 code snippet::
620
620
621 import IPython
621 import IPython
622
622
623 a = 42
623 a = 42
624 IPython.embed()
624 IPython.embed()
625
625
626 and within the IPython shell, you reassign `a` to `23` to do further testing of
626 and within the IPython shell, you reassign `a` to `23` to do further testing of
627 some sort, you can then exit::
627 some sort, you can then exit::
628
628
629 >>> IPython.embed()
629 >>> IPython.embed()
630 Python 3.6.2 (default, Jul 17 2017, 16:44:45)
630 Python 3.6.2 (default, Jul 17 2017, 16:44:45)
631 Type 'copyright', 'credits' or 'license' for more information
631 Type 'copyright', 'credits' or 'license' for more information
632 IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help.
632 IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help.
633
633
634 In [1]: a = 23
634 In [1]: a = 23
635
635
636 In [2]: exit()
636 In [2]: exit()
637
637
638 Once you exit and print `a`, the value 23 will be shown::
638 Once you exit and print `a`, the value 23 will be shown::
639
639
640
640
641 In: print(a)
641 In: print(a)
642 23
642 23
643
643
644 It's important to note that the code run in the embedded IPython shell will
644 It's important to note that the code run in the embedded IPython shell will
645 *not* change the state of your code and variables, **unless** the shell is
645 *not* change the state of your code and variables, **unless** the shell is
646 contained within the global namespace. In the above example, `a` is changed
646 contained within the global namespace. In the above example, `a` is changed
647 because this is true.
647 because this is true.
648
648
649 To further exemplify this, consider the following example::
649 To further exemplify this, consider the following example::
650
650
651 import IPython
651 import IPython
652 def do():
652 def do():
653 a = 42
653 a = 42
654 print(a)
654 print(a)
655 IPython.embed()
655 IPython.embed()
656 print(a)
656 print(a)
657
657
658 Now if call the function and complete the state changes as we did above, the
658 Now if call the function and complete the state changes as we did above, the
659 value `42` will be printed. Again, this is because it's not in the global
659 value `42` will be printed. Again, this is because it's not in the global
660 namespace::
660 namespace::
661
661
662 do()
662 do()
663
663
664 Running a file with the above code can lead to the following session::
664 Running a file with the above code can lead to the following session::
665
665
666 >>> do()
666 >>> do()
667 42
667 42
668 Python 3.6.2 (default, Jul 17 2017, 16:44:45)
668 Python 3.6.2 (default, Jul 17 2017, 16:44:45)
669 Type 'copyright', 'credits' or 'license' for more information
669 Type 'copyright', 'credits' or 'license' for more information
670 IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help.
670 IPython 6.2.0.dev -- An enhanced Interactive Python. Type '?' for help.
671
671
672 In [1]: a = 23
672 In [1]: a = 23
673
673
674 In [2]: exit()
674 In [2]: exit()
675 42
675 42
676
676
677 .. note::
677 .. note::
678
678
679 At present, embedding IPython cannot be done from inside IPython.
679 At present, embedding IPython cannot be done from inside IPython.
680 Run the code samples below outside IPython.
680 Run the code samples below outside IPython.
681
681
682 This feature allows you to easily have a fully functional python
682 This feature allows you to easily have a fully functional python
683 environment for doing object introspection anywhere in your code with a
683 environment for doing object introspection anywhere in your code with a
684 simple function call. In some cases a simple print statement is enough,
684 simple function call. In some cases a simple print statement is enough,
685 but if you need to do more detailed analysis of a code fragment this
685 but if you need to do more detailed analysis of a code fragment this
686 feature can be very valuable.
686 feature can be very valuable.
687
687
688 It can also be useful in scientific computing situations where it is
688 It can also be useful in scientific computing situations where it is
689 common to need to do some automatic, computationally intensive part and
689 common to need to do some automatic, computationally intensive part and
690 then stop to look at data, plots, etc.
690 then stop to look at data, plots, etc.
691 Opening an IPython instance will give you full access to your data and
691 Opening an IPython instance will give you full access to your data and
692 functions, and you can resume program execution once you are done with
692 functions, and you can resume program execution once you are done with
693 the interactive part (perhaps to stop again later, as many times as
693 the interactive part (perhaps to stop again later, as many times as
694 needed).
694 needed).
695
695
696 The following code snippet is the bare minimum you need to include in
696 The following code snippet is the bare minimum you need to include in
697 your Python programs for this to work (detailed examples follow later)::
697 your Python programs for this to work (detailed examples follow later)::
698
698
699 from IPython import embed
699 from IPython import embed
700
700
701 embed() # this call anywhere in your program will start IPython
701 embed() # this call anywhere in your program will start IPython
702
702
703 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
703 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
704 ``IPython.embed_kernel()``. This should work the same way, but you can
704 ``IPython.embed_kernel()``. This should work the same way, but you can
705 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
705 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
706 rather than interacting with it in the terminal.
706 rather than interacting with it in the terminal.
707
707
708 You can run embedded instances even in code which is itself being run at
708 You can run embedded instances even in code which is itself being run at
709 the IPython interactive prompt with '%run <filename>'. Since it's easy
709 the IPython interactive prompt with '%run <filename>'. Since it's easy
710 to get lost as to where you are (in your top-level IPython or in your
710 to get lost as to where you are (in your top-level IPython or in your
711 embedded one), it's a good idea in such cases to set the in/out prompts
711 embedded one), it's a good idea in such cases to set the in/out prompts
712 to something different for the embedded instances. The code examples
712 to something different for the embedded instances. The code examples
713 below illustrate this.
713 below illustrate this.
714
714
715 You can also have multiple IPython instances in your program and open
715 You can also have multiple IPython instances in your program and open
716 them separately, for example with different options for data
716 them separately, for example with different options for data
717 presentation. If you close and open the same instance multiple times,
717 presentation. If you close and open the same instance multiple times,
718 its prompt counters simply continue from each execution to the next.
718 its prompt counters simply continue from each execution to the next.
719
719
720 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
720 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
721 module for more details on the use of this system.
721 module for more details on the use of this system.
722
722
723 The following sample file illustrating how to use the embedding
723 The following sample file illustrating how to use the embedding
724 functionality is provided in the examples directory as embed_class_long.py.
724 functionality is provided in the examples directory as embed_class_long.py.
725 It should be fairly self-explanatory:
725 It should be fairly self-explanatory:
726
726
727 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
727 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
728 :language: python
728 :language: python
729
729
730 Once you understand how the system functions, you can use the following
730 Once you understand how the system functions, you can use the following
731 code fragments in your programs which are ready for cut and paste:
731 code fragments in your programs which are ready for cut and paste:
732
732
733 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
733 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
734 :language: python
734 :language: python
735
735
736 Using the Python debugger (pdb)
736 Using the Python debugger (pdb)
737 ===============================
737 ===============================
738
738
739 Running entire programs via pdb
739 Running entire programs via pdb
740 -------------------------------
740 -------------------------------
741
741
742 pdb, the Python debugger, is a powerful interactive debugger which
742 pdb, the Python debugger, is a powerful interactive debugger which
743 allows you to step through code, set breakpoints, watch variables,
743 allows you to step through code, set breakpoints, watch variables,
744 etc. IPython makes it very easy to start any script under the control
744 etc. IPython makes it very easy to start any script under the control
745 of pdb, regardless of whether you have wrapped it into a 'main()'
745 of pdb, regardless of whether you have wrapped it into a 'main()'
746 function or not. For this, simply type ``%run -d myscript`` at an
746 function or not. For this, simply type ``%run -d myscript`` at an
747 IPython prompt. See the :magic:`run` command's documentation for more details, including
747 IPython prompt. See the :magic:`run` command's documentation for more details, including
748 how to control where pdb will stop execution first.
748 how to control where pdb will stop execution first.
749
749
750 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
750 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
751 in the Python documentation.
751 in the Python documentation.
752
752
753 IPython extends the debugger with a few useful additions, like coloring of
753 IPython extends the debugger with a few useful additions, like coloring of
754 tracebacks. The debugger will adopt the color scheme selected for IPython.
754 tracebacks. The debugger will adopt the color scheme selected for IPython.
755
755
756 The ``where`` command has also been extended to take as argument the number of
756 The ``where`` command has also been extended to take as argument the number of
757 context line to show. This allows to a many line of context on shallow stack trace:
757 context line to show. This allows to a many line of context on shallow stack trace:
758
758
759 .. code::
759 .. code::
760
760
761 In [5]: def foo(x):
761 In [5]: def foo(x):
762 ...: 1
762 ...: 1
763 ...: 2
763 ...: 2
764 ...: 3
764 ...: 3
765 ...: return 1/x+foo(x-1)
765 ...: return 1/x+foo(x-1)
766 ...: 5
766 ...: 5
767 ...: 6
767 ...: 6
768 ...: 7
768 ...: 7
769 ...:
769 ...:
770
770
771 In[6]: foo(1)
771 In[6]: foo(1)
772 # ...
772 # ...
773 ipdb> where 8
773 ipdb> where 8
774 <ipython-input-6-9e45007b2b59>(1)<module>
774 <ipython-input-6-9e45007b2b59>(1)<module>
775 ----> 1 foo(1)
775 ----> 1 foo(1)
776
776
777 <ipython-input-5-7baadc3d1465>(5)foo()
777 <ipython-input-5-7baadc3d1465>(5)foo()
778 1 def foo(x):
778 1 def foo(x):
779 2 1
779 2 1
780 3 2
780 3 2
781 4 3
781 4 3
782 ----> 5 return 1/x+foo(x-1)
782 ----> 5 return 1/x+foo(x-1)
783 6 5
783 6 5
784 7 6
784 7 6
785 8 7
785 8 7
786
786
787 > <ipython-input-5-7baadc3d1465>(5)foo()
787 > <ipython-input-5-7baadc3d1465>(5)foo()
788 1 def foo(x):
788 1 def foo(x):
789 2 1
789 2 1
790 3 2
790 3 2
791 4 3
791 4 3
792 ----> 5 return 1/x+foo(x-1)
792 ----> 5 return 1/x+foo(x-1)
793 6 5
793 6 5
794 7 6
794 7 6
795 8 7
795 8 7
796
796
797
797
798 And less context on shallower Stack Trace:
798 And less context on shallower Stack Trace:
799
799
800 .. code::
800 .. code::
801
801
802 ipdb> where 1
802 ipdb> where 1
803 <ipython-input-13-afa180a57233>(1)<module>
803 <ipython-input-13-afa180a57233>(1)<module>
804 ----> 1 foo(7)
804 ----> 1 foo(7)
805
805
806 <ipython-input-5-7baadc3d1465>(5)foo()
806 <ipython-input-5-7baadc3d1465>(5)foo()
807 ----> 5 return 1/x+foo(x-1)
807 ----> 5 return 1/x+foo(x-1)
808
808
809 <ipython-input-5-7baadc3d1465>(5)foo()
809 <ipython-input-5-7baadc3d1465>(5)foo()
810 ----> 5 return 1/x+foo(x-1)
810 ----> 5 return 1/x+foo(x-1)
811
811
812 <ipython-input-5-7baadc3d1465>(5)foo()
812 <ipython-input-5-7baadc3d1465>(5)foo()
813 ----> 5 return 1/x+foo(x-1)
813 ----> 5 return 1/x+foo(x-1)
814
814
815 <ipython-input-5-7baadc3d1465>(5)foo()
815 <ipython-input-5-7baadc3d1465>(5)foo()
816 ----> 5 return 1/x+foo(x-1)
816 ----> 5 return 1/x+foo(x-1)
817
817
818
818
819 Post-mortem debugging
819 Post-mortem debugging
820 ---------------------
820 ---------------------
821
821
822 Going into a debugger when an exception occurs can be
822 Going into a debugger when an exception occurs can be
823 extremely useful in order to find the origin of subtle bugs, because pdb
823 extremely useful in order to find the origin of subtle bugs, because pdb
824 opens up at the point in your code which triggered the exception, and
824 opens up at the point in your code which triggered the exception, and
825 while your program is at this point 'dead', all the data is still
825 while your program is at this point 'dead', all the data is still
826 available and you can walk up and down the stack frame and understand
826 available and you can walk up and down the stack frame and understand
827 the origin of the problem.
827 the origin of the problem.
828
828
829 You can use the :magic:`debug` magic after an exception has occurred to start
829 You can use the :magic:`debug` magic after an exception has occurred to start
830 post-mortem debugging. IPython can also call debugger every time your code
830 post-mortem debugging. IPython can also call debugger every time your code
831 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
831 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
832 command, or you can start IPython with the ``--pdb`` option.
832 command, or you can start IPython with the ``--pdb`` option.
833
833
834 For a post-mortem debugger in your programs outside IPython,
834 For a post-mortem debugger in your programs outside IPython,
835 put the following lines toward the top of your 'main' routine::
835 put the following lines toward the top of your 'main' routine::
836
836
837 import sys
837 import sys
838 from IPython.core import ultratb
838 from IPython.core import ultratb
839 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
839 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
840 color_scheme='Linux', call_pdb=1)
840 color_scheme='Linux', call_pdb=1)
841
841
842 The mode keyword can be either 'Verbose' or 'Plain', giving either very
842 The mode keyword can be either 'Verbose' or 'Plain', giving either very
843 detailed or normal tracebacks respectively. The color_scheme keyword can
843 detailed or normal tracebacks respectively. The color_scheme keyword can
844 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
844 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
845 options which can be set in IPython with ``--colors`` and ``--xmode``.
845 options which can be set in IPython with ``--colors`` and ``--xmode``.
846
846
847 This will give any of your programs detailed, colored tracebacks with
847 This will give any of your programs detailed, colored tracebacks with
848 automatic invocation of pdb.
848 automatic invocation of pdb.
849
849
850 .. _pasting_with_prompts:
850 .. _pasting_with_prompts:
851
851
852 Pasting of code starting with Python or IPython prompts
852 Pasting of code starting with Python or IPython prompts
853 =======================================================
853 =======================================================
854
854
855 IPython is smart enough to filter out input prompts, be they plain Python ones
855 IPython is smart enough to filter out input prompts, be they plain Python ones
856 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
856 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
857 therefore copy and paste from existing interactive sessions without worry.
857 therefore copy and paste from existing interactive sessions without worry.
858
858
859 The following is a 'screenshot' of how things work, copying an example from the
859 The following is a 'screenshot' of how things work, copying an example from the
860 standard Python tutorial::
860 standard Python tutorial::
861
861
862 In [1]: >>> # Fibonacci series:
862 In [1]: >>> # Fibonacci series:
863
863
864 In [2]: ... # the sum of two elements defines the next
864 In [2]: ... # the sum of two elements defines the next
865
865
866 In [3]: ... a, b = 0, 1
866 In [3]: ... a, b = 0, 1
867
867
868 In [4]: >>> while b < 10:
868 In [4]: >>> while b < 10:
869 ...: ... print(b)
869 ...: ... print(b)
870 ...: ... a, b = b, a+b
870 ...: ... a, b = b, a+b
871 ...:
871 ...:
872 1
872 1
873 1
873 1
874 2
874 2
875 3
875 3
876 5
876 5
877 8
877 8
878
878
879 And pasting from IPython sessions works equally well::
879 And pasting from IPython sessions works equally well::
880
880
881 In [1]: In [5]: def f(x):
881 In [1]: In [5]: def f(x):
882 ...: ...: "A simple function"
882 ...: ...: "A simple function"
883 ...: ...: return x**2
883 ...: ...: return x**2
884 ...: ...:
884 ...: ...:
885
885
886 In [2]: f(3)
886 In [2]: f(3)
887 Out[2]: 9
887 Out[2]: 9
888
888
889 .. _gui_support:
889 .. _gui_support:
890
890
891 GUI event loop support
891 GUI event loop support
892 ======================
892 ======================
893
893
894 IPython has excellent support for working interactively with Graphical User
894 IPython has excellent support for working interactively with Graphical User
895 Interface (GUI) toolkits, such as wxPython, PyQt/PySide, PyGTK and Tk. This is
895 Interface (GUI) toolkits, such as wxPython, PyQt/PySide, PyGTK and Tk. This is
896 implemented by running the toolkit's event loop while IPython is waiting for
896 implemented by running the toolkit's event loop while IPython is waiting for
897 input.
897 input.
898
898
899 For users, enabling GUI event loop integration is simple. You simple use the
899 For users, enabling GUI event loop integration is simple. You simple use the
900 :magic:`gui` magic as follows::
900 :magic:`gui` magic as follows::
901
901
902 %gui [GUINAME]
902 %gui [GUINAME]
903
903
904 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
904 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
905 arguments include ``wx``, ``qt``, ``qt5``, ``qt6``, ``gtk``, ``gtk3`` ``gtk4``, and
905 arguments include ``wx``, ``qt``, ``qt5``, ``qt6``, ``gtk3`` ``gtk4``, and
906 ``tk``.
906 ``tk``.
907
907
908 Thus, to use wxPython interactively and create a running :class:`wx.App`
908 Thus, to use wxPython interactively and create a running :class:`wx.App`
909 object, do::
909 object, do::
910
910
911 %gui wx
911 %gui wx
912
912
913 You can also start IPython with an event loop set up using the `--gui`
913 You can also start IPython with an event loop set up using the `--gui`
914 flag::
914 flag::
915
915
916 $ ipython --gui=qt
916 $ ipython --gui=qt
917
917
918 For information on IPython's matplotlib_ integration (and the ``matplotlib``
918 For information on IPython's matplotlib_ integration (and the ``matplotlib``
919 mode) see :ref:`this section <matplotlib_support>`.
919 mode) see :ref:`this section <matplotlib_support>`.
920
920
921 For developers that want to integrate additional event loops with IPython, see
921 For developers that want to integrate additional event loops with IPython, see
922 :doc:`/config/eventloops`.
922 :doc:`/config/eventloops`.
923
923
924 When running inside IPython with an integrated event loop, a GUI application
924 When running inside IPython with an integrated event loop, a GUI application
925 should *not* start its own event loop. This means that applications that are
925 should *not* start its own event loop. This means that applications that are
926 meant to be used both
926 meant to be used both
927 in IPython and as standalone apps need to have special code to detects how the
927 in IPython and as standalone apps need to have special code to detects how the
928 application is being run. We highly recommend using IPython's support for this.
928 application is being run. We highly recommend using IPython's support for this.
929 Since the details vary slightly between toolkits, we point you to the various
929 Since the details vary slightly between toolkits, we point you to the various
930 examples in our source directory :file:`examples/IPython Kernel/gui/` that
930 examples in our source directory :file:`examples/IPython Kernel/gui/` that
931 demonstrate these capabilities.
931 demonstrate these capabilities.
932
932
933 PyQt and PySide
933 PyQt and PySide
934 ---------------
934 ---------------
935
935
936 .. attempt at explanation of the complete mess that is Qt support
936 .. attempt at explanation of the complete mess that is Qt support
937
937
938 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
938 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
939 PyQt or PySide. ``qt`` implies "use the latest version available", and it favors
939 PyQt or PySide. ``qt`` implies "use the latest version available", and it favors
940 PyQt over PySide. To request a specific version, use ``qt5`` or ``qt6``. Note that
940 PyQt over PySide. To request a specific version, use ``qt5`` or ``qt6``.
941 Qt4 is not supported with the ``--gui`` switch (and has not been for some time now).
942
941
943 If specified, IPython will respect the environment variable ``QT_API`` used
942 If specified, IPython will respect the environment variable ``QT_API``. If
944 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
943 ``QT_API`` is not specified and you launch IPython in matplotlib mode with
945 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
944 ``ipython --matplotlib=qt`` then IPython will ask matplotlib which Qt library
946 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
945 to use. See the matplotlib_ documentation on ``QT_API`` for further details.
947 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
948
949 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
950 then IPython will ask matplotlib which Qt library to use (only if QT_API is
951 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
952 older, then IPython will always use PyQt4 without setting the v2 APIs, since
953 neither v2 PyQt nor PySide work.
954
955 .. warning::
956
957 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
958 to work with IPython's qt integration, because otherwise PyQt4 will be
959 loaded in an incompatible mode.
960
961 It also means that you must *not* have ``QT_API`` set if you want to
962 use ``--gui=qt`` with code that requires PyQt4 API v1.
963
946
964
947
965 .. _matplotlib_support:
948 .. _matplotlib_support:
966
949
967 Plotting with matplotlib
950 Plotting with matplotlib
968 ========================
951 ========================
969
952
970 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
953 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
971 can produce plots on screen using a variety of GUI toolkits, including Tk,
954 can produce plots on screen using a variety of GUI toolkits, including Tk,
972 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
955 PyGTK, PyQt6 and wxPython. It also provides a number of commands useful for
973 scientific computing, all with a syntax compatible with that of the popular
956 scientific computing, all with a syntax compatible with that of the popular
974 Matlab program.
957 Matlab program.
975
958
976 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
959 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
977 IPython is already running, you can run the :magic:`matplotlib` magic. If no
960 IPython is already running, you can run the :magic:`matplotlib` magic. If no
978 arguments are given, IPython will automatically detect your choice of
961 arguments are given, IPython will automatically detect your choice of
979 matplotlib backend. You can also request a specific backend with
962 matplotlib backend. For information on matplotlib backends see
980 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
963 :ref:`matplotlib_magic`.
981 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
964
982 backend value, which produces static figures inlined inside the application
983 window instead of matplotlib's interactive figures that live in separate
984 windows.
985
965
986 .. _interactive_demos:
966 .. _interactive_demos:
987
967
988 Interactive demos with IPython
968 Interactive demos with IPython
989 ==============================
969 ==============================
990
970
991 IPython ships with a basic system for running scripts interactively in
971 IPython ships with a basic system for running scripts interactively in
992 sections, useful when presenting code to audiences. A few tags embedded
972 sections, useful when presenting code to audiences. A few tags embedded
993 in comments (so that the script remains valid Python code) divide a file
973 in comments (so that the script remains valid Python code) divide a file
994 into separate blocks, and the demo can be run one block at a time, with
974 into separate blocks, and the demo can be run one block at a time, with
995 IPython printing (with syntax highlighting) the block before executing
975 IPython printing (with syntax highlighting) the block before executing
996 it, and returning to the interactive prompt after each block. The
976 it, and returning to the interactive prompt after each block. The
997 interactive namespace is updated after each block is run with the
977 interactive namespace is updated after each block is run with the
998 contents of the demo's namespace.
978 contents of the demo's namespace.
999
979
1000 This allows you to show a piece of code, run it and then execute
980 This allows you to show a piece of code, run it and then execute
1001 interactively commands based on the variables just created. Once you
981 interactively commands based on the variables just created. Once you
1002 want to continue, you simply execute the next block of the demo. The
982 want to continue, you simply execute the next block of the demo. The
1003 following listing shows the markup necessary for dividing a script into
983 following listing shows the markup necessary for dividing a script into
1004 sections for execution as a demo:
984 sections for execution as a demo:
1005
985
1006 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
986 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
1007 :language: python
987 :language: python
1008
988
1009 In order to run a file as a demo, you must first make a Demo object out
989 In order to run a file as a demo, you must first make a Demo object out
1010 of it. If the file is named myscript.py, the following code will make a
990 of it. If the file is named myscript.py, the following code will make a
1011 demo::
991 demo::
1012
992
1013 from IPython.lib.demo import Demo
993 from IPython.lib.demo import Demo
1014
994
1015 mydemo = Demo('myscript.py')
995 mydemo = Demo('myscript.py')
1016
996
1017 This creates the mydemo object, whose blocks you run one at a time by
997 This creates the mydemo object, whose blocks you run one at a time by
1018 simply calling the object with no arguments. Then call it to run each step
998 simply calling the object with no arguments. Then call it to run each step
1019 of the demo::
999 of the demo::
1020
1000
1021 mydemo()
1001 mydemo()
1022
1002
1023 Demo objects can be
1003 Demo objects can be
1024 restarted, you can move forward or back skipping blocks, re-execute the
1004 restarted, you can move forward or back skipping blocks, re-execute the
1025 last block, etc. See the :mod:`IPython.lib.demo` module and the
1005 last block, etc. See the :mod:`IPython.lib.demo` module and the
1026 :class:`~IPython.lib.demo.Demo` class for details.
1006 :class:`~IPython.lib.demo.Demo` class for details.
1027
1007
1028 Limitations: These demos are limited to
1008 Limitations: These demos are limited to
1029 fairly simple uses. In particular, you cannot break up sections within
1009 fairly simple uses. In particular, you cannot break up sections within
1030 indented code (loops, if statements, function definitions, etc.)
1010 indented code (loops, if statements, function definitions, etc.)
1031 Supporting something like this would basically require tracking the
1011 Supporting something like this would basically require tracking the
1032 internal execution state of the Python interpreter, so only top-level
1012 internal execution state of the Python interpreter, so only top-level
1033 divisions are allowed. If you want to be able to open an IPython
1013 divisions are allowed. If you want to be able to open an IPython
1034 instance at an arbitrary point in a program, you can use IPython's
1014 instance at an arbitrary point in a program, you can use IPython's
1035 :ref:`embedding facilities <Embedding>`.
1015 :ref:`embedding facilities <Embedding>`.
1036
1016
1037 .. include:: ../links.txt
1017 .. include:: ../links.txt
@@ -1,2268 +1,2268 b''
1 ============
1 ============
2 8.x Series
2 8.x Series
3 ============
3 ============
4
4
5 .. _version 8.24:
5 .. _version 8.24:
6
6
7 IPython 8.24
7 IPython 8.24
8 ============
8 ============
9
9
10 Back on regular release schedule, as usual month releases are relatively tiny.
10 Back on regular release schedule, as usual month releases are relatively tiny.
11
11
12 The biggest change is the move of the matplotlib backend handling from IPython
12 The biggest change is the move of the matplotlib backend handling from IPython
13 to matplotlib. :ghpull:`14371`:ghpull:`14403`.
13 to matplotlib. :ghpull:`14371` :ghpull:`14403`.
14
14
15 We will note:
15 We will note:
16
16
17 - pytest 8 compatibility :ghpull:`14413`
17 - pytest 8 compatibility :ghpull:`14413`
18 - ``typing-extension`` now needs 4.6 or newer. It was already the case, but not
18 - ``typing-extension`` now needs 4.6 or newer. It was already the case, but not
19 explicated. :ghpull:`14380`
19 explicated. :ghpull:`14380`
20 - Attempt to speed running code under debugger in some cases. :ghpull:`14386`
20 - Attempt to speed running code under debugger in some cases. :ghpull:`14386`
21 :ghpull:`14418`.
21 :ghpull:`14418`.
22 - Multiple fixes to documentation for ipyparallel, simple_prompt and emacs
22 - Multiple fixes to documentation for ipyparallel, simple_prompt and emacs
23 :ghpull:`14384` :ghpull:`14404` :ghpull:`14407`
23 :ghpull:`14384` :ghpull:`14404` :ghpull:`14407`
24 - Maintenance and cleanup of debugger :ghpull:`14387` :ghpull:`14393`
24 - Maintenance and cleanup of debugger :ghpull:`14387` :ghpull:`14393`
25
25
26 As usual you can find the full list of PRs on GitHub under `the 8.24
26 As usual you can find the full list of PRs on GitHub under `the 8.24
27 <https://github.com/ipython/ipython/milestone/131?closed=1>`__ milestone.
27 <https://github.com/ipython/ipython/milestone/131?closed=1>`__ milestone.
28
28
29 Thanks
29 Thanks
30 ------
30 ------
31
31
32 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
32 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
33 work on IPython and related libraries.
33 work on IPython and related libraries.
34
34
35
35
36 .. _version 8.23:
36 .. _version 8.23:
37
37
38 IPython 8.23
38 IPython 8.23
39 ============
39 ============
40
40
41 Super tiny release of IPython on Sunday – a bit later than usual, which is also
41 Super tiny release of IPython on Sunday – a bit later than usual, which is also
42 `πŸ³οΈβ€βš§οΈ International Transgender Day of VisibilityπŸ³οΈβ€βš§οΈ
42 `πŸ³οΈβ€βš§οΈ International Transgender Day of VisibilityπŸ³οΈβ€βš§οΈ
43 <https://en.wikipedia.org/wiki/International_Transgender_Day_of_Visibility>`_ –
43 <https://en.wikipedia.org/wiki/International_Transgender_Day_of_Visibility>`_ –
44 so a though for you on this day, you matter and you are valid [1]_.
44 so a though for you on this day, you matter and you are valid [1]_.
45
45
46 This is a minuscule release with only 5 Pull requests.
46 This is a minuscule release with only 5 Pull requests.
47
47
48 Main change is :ghpull:`14357` which improve inference from return type
48 Main change is :ghpull:`14357` which improve inference from return type
49 annotations in completer and the introduction of the optional target
49 annotations in completer and the introduction of the optional target
50 ``ipython[matplotlib]`` to explicitly request the matplotlib optional
50 ``ipython[matplotlib]`` to explicitly request the matplotlib optional
51 dependencies.
51 dependencies.
52
52
53 As usual you can find the full list of PRs on GitHub under `the 8.23
53 As usual you can find the full list of PRs on GitHub under `the 8.23
54 <https://github.com/ipython/ipython/milestone/130?closed=1>`__ milestone.
54 <https://github.com/ipython/ipython/milestone/130?closed=1>`__ milestone.
55
55
56 Thanks
56 Thanks
57 ------
57 ------
58
58
59 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
59 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
60 work on IPython and related libraries.
60 work on IPython and related libraries.
61
61
62
62
63 .. _version 8.22:
63 .. _version 8.22:
64
64
65 IPython 8.22, 8.22.1 and 8.22.2
65 IPython 8.22, 8.22.1 and 8.22.2
66 ===============================
66 ===============================
67
67
68 Quick release of IPython for this short month of February, with quite a bit of
68 Quick release of IPython for this short month of February, with quite a bit of
69 activity with more than 15 PRs.
69 activity with more than 15 PRs.
70
70
71 I am not going to details all the changes, but among other we have :
71 I am not going to details all the changes, but among other we have :
72
72
73 - More compatibility with emscripten :ghpull:`14316`, :ghpull:`14318`,
73 - More compatibility with emscripten :ghpull:`14316`, :ghpull:`14318`,
74 - Test more downstream project to avoid breakage :ghpull:`14317`
74 - Test more downstream project to avoid breakage :ghpull:`14317`
75 - Fix recently introduced bug with the ``store`` magic.
75 - Fix recently introduced bug with the ``store`` magic.
76 - Fix issues with multiple call to ``matplotlib.pyplot.switch_backend``
76 - Fix issues with multiple call to ``matplotlib.pyplot.switch_backend``
77 - Fix crashing IPython when some tracebacks encounter dynamically evaluated
77 - Fix crashing IPython when some tracebacks encounter dynamically evaluated
78 code.
78 code.
79
79
80 IPython 8.22.1 increase the minimal traitlets version, and 8.22.2 fix a critical
80 IPython 8.22.1 increase the minimal traitlets version, and 8.22.2 fix a critical
81 bug on emscripten preventing to use some magics like ``%matplotlib`` on
81 bug on emscripten preventing to use some magics like ``%matplotlib`` on
82 jupyter-light.
82 jupyter-light.
83
83
84 API changes
84 API changes
85 -----------
85 -----------
86
86
87 One of the largest change is the update the mimehooks and inspector API, see
87 One of the largest change is the update the mimehooks and inspector API, see
88 :ghpull:`14342`. It should be backward compatible, but many hooks now receive a
88 :ghpull:`14342`. It should be backward compatible, but many hooks now receive a
89 single object with many fields allowing us flexibility to update the API later.
89 single object with many fields allowing us flexibility to update the API later.
90
90
91
91
92 Packaging changes
92 Packaging changes
93 -----------------
93 -----------------
94
94
95 Thanks to `@mkoppe <https://github.com/mkoeppe>`__, we are slowly getting rid of
95 Thanks to `@mkoppe <https://github.com/mkoeppe>`__, we are slowly getting rid of
96 setup.py finally migrating to ``pyproject.toml``. There is still quite a bit of
96 setup.py finally migrating to ``pyproject.toml``. There is still quite a bit of
97 work, and please open an issue if you encounter any problem.
97 work, and please open an issue if you encounter any problem.
98
98
99
99
100 Deprecation
100 Deprecation
101 -----------
101 -----------
102
102
103 A number of unused functions have been marked deprecated or pending deprecation.
103 A number of unused functions have been marked deprecated or pending deprecation.
104 Please let us know if you encounter any of those deprecation messages for us to
104 Please let us know if you encounter any of those deprecation messages for us to
105 adjust the removal timeline.
105 adjust the removal timeline.
106
106
107
107
108 Thanks
108 Thanks
109 ------
109 ------
110
110
111 Many thanks to `@mkoppe <https://github.com/mkoeppe>`__ and `@krassowski
111 Many thanks to `@mkoppe <https://github.com/mkoeppe>`__ and `@krassowski
112 <https://github.com/krassowski>`__ for their multiple contributions and codebase
112 <https://github.com/krassowski>`__ for their multiple contributions and codebase
113 cleanup.
113 cleanup.
114
114
115 As usual you can find the full list of PRs on GitHub under `the 8.22
115 As usual you can find the full list of PRs on GitHub under `the 8.22
116 <https://github.com/ipython/ipython/milestone/129?closed=1>`__ milestone.
116 <https://github.com/ipython/ipython/milestone/129?closed=1>`__ milestone.
117
117
118 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
118 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
119 work on IPython and related libraries.
119 work on IPython and related libraries.
120
120
121
121
122 .. _version 8.21:
122 .. _version 8.21:
123
123
124 IPython 8.21
124 IPython 8.21
125 ------------
125 ------------
126
126
127 More substantial release of IPython slightly out of schedule as it was not
127 More substantial release of IPython slightly out of schedule as it was not
128 possible for me to make a release last Friday.
128 possible for me to make a release last Friday.
129
129
130 Few new features are present, but the codebase has been cleaned, and a couple
130 Few new features are present, but the codebase has been cleaned, and a couple
131 of API are _considered_ for deprecation. They are not deprecated yet, but as
131 of API are _considered_ for deprecation. They are not deprecated yet, but as
132 they do not seem to be quite used, they may emit a warning, in which case please
132 they do not seem to be quite used, they may emit a warning, in which case please
133 comment on the relevant issue to inform me of _which_ project use those feature
133 comment on the relevant issue to inform me of _which_ project use those feature
134 and how you use them. Depending on the feedback I might change the timeline for
134 and how you use them. Depending on the feedback I might change the timeline for
135 deprecation.
135 deprecation.
136
136
137 This release saw 14 PRs, with more outside contribution than usual,
137 This release saw 14 PRs, with more outside contribution than usual,
138 I'll note in particular PRs related to making IPython work on emscripten.
138 I'll note in particular PRs related to making IPython work on emscripten.
139
139
140 I also want to point that we are _trying_ to keep compatibility with Python 3.13,
140 I also want to point that we are _trying_ to keep compatibility with Python 3.13,
141 but it's a cat and mouse game. Plus I am low on time, so I would appreciate any
141 but it's a cat and mouse game. Plus I am low on time, so I would appreciate any
142 help with that.
142 help with that.
143
143
144 Deprecations
144 Deprecations
145 ~~~~~~~~~~~~
145 ~~~~~~~~~~~~
146
146
147 - :ghpull:`14307` Pending Deprecation of
147 - :ghpull:`14307` Pending Deprecation of
148 ``ColorSchemeTable.set_active_scheme(...)``'s ``case_sensitive`` Parameter.
148 ``ColorSchemeTable.set_active_scheme(...)``'s ``case_sensitive`` Parameter.
149 - :ghpull:`14305` Pending Deprecation of constructing ``ColorScheme`` via
149 - :ghpull:`14305` Pending Deprecation of constructing ``ColorScheme`` via
150 ``kwargs``, in favor passing a single dict.
150 ``kwargs``, in favor passing a single dict.
151
151
152
152
153 Fixes
153 Fixes
154 ~~~~~
154 ~~~~~
155
155
156 - :ghpull:`14284` TerminalIPythonApp's would warn that ``auto_create`` option is not
156 - :ghpull:`14284` TerminalIPythonApp's would warn that ``auto_create`` option is not
157 recognized.
157 recognized.
158 - :ghpull:`14286` Fix a crash with ``NotOneValueFound`` when rendering complex
158 - :ghpull:`14286` Fix a crash with ``NotOneValueFound`` when rendering complex
159 tracebacks.
159 tracebacks.
160
160
161 - :ghpull:`14287` Partial Python 3.13 compatibility
161 - :ghpull:`14287` Partial Python 3.13 compatibility
162 - :ghpull:`14290` Docs/Typos.
162 - :ghpull:`14290` Docs/Typos.
163
163
164 Changes
164 Changes
165 ~~~~~~~
165 ~~~~~~~
166
166
167 - :ghpull:`14289` ``ipdb.set_trace()`` now accepts ``header=`` for better
167 - :ghpull:`14289` ``ipdb.set_trace()`` now accepts ``header=`` for better
168 compatibility with ``pdb.set_trace()``
168 compatibility with ``pdb.set_trace()``
169
169
170 - :ghpull:`14300` and :ghpull:`14301` Add hooking ability to produce
170 - :ghpull:`14300` and :ghpull:`14301` Add hooking ability to produce
171 mimebundle.
171 mimebundle.
172
172
173 We'll outline :ghpull:`14300`, it is now possible to extend the ``?/??``
173 We'll outline :ghpull:`14300`, it is now possible to extend the ``?/??``
174 operator to return more mimetypes to render richer help in frontends that
174 operator to return more mimetypes to render richer help in frontends that
175 support it. In particular you could send a json representation of the help that
175 support it. In particular you could send a json representation of the help that
176 could be displayed in a customizable way.
176 could be displayed in a customizable way.
177
177
178 Miscellaneous
178 Miscellaneous
179 ~~~~~~~~~~~~~
179 ~~~~~~~~~~~~~
180
180
181 - :ghpull:`14291` Misc Refactor of Color handling
181 - :ghpull:`14291` Misc Refactor of Color handling
182 - :ghpull:`14295` Misc test skip on problematic Pypy versions.
182 - :ghpull:`14295` Misc test skip on problematic Pypy versions.
183
183
184
184
185 Thanks
185 Thanks
186 ~~~~~~
186 ~~~~~~
187
187
188 Special thanks to all our contributors, and to the Pypy team that was extremely
188 Special thanks to all our contributors, and to the Pypy team that was extremely
189 reactive in helping to investigate a fixing a rare unicode+windows bug.
189 reactive in helping to investigate a fixing a rare unicode+windows bug.
190
190
191 As usual you can find the full list of PRs on GitHub under `the 8.21
191 As usual you can find the full list of PRs on GitHub under `the 8.21
192 <https://github.com/ipython/ipython/milestone/128?closed=1>`__ milestone.
192 <https://github.com/ipython/ipython/milestone/128?closed=1>`__ milestone.
193
193
194 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
194 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
195 work on IPython and related libraries.
195 work on IPython and related libraries.
196
196
197
197
198 .. _version 8.20:
198 .. _version 8.20:
199
199
200 IPython 8.20
200 IPython 8.20
201 ------------
201 ------------
202
202
203 Quick IPython release in this beginning of 2024, barely 2 weeks after the previous
203 Quick IPython release in this beginning of 2024, barely 2 weeks after the previous
204 release.
204 release.
205
205
206 This is mostly to fix a backward compatibility issue, I would have done a patch
206 This is mostly to fix a backward compatibility issue, I would have done a patch
207 release earlier if I could. As a few other cleanup are also part of this
207 release earlier if I could. As a few other cleanup are also part of this
208 release, this will get a minor version bump.
208 release, this will get a minor version bump.
209
209
210
210
211 The crux of this release is :ghpull:`14274` (Inspect continuation prompt
211 The crux of this release is :ghpull:`14274` (Inspect continuation prompt
212 signature and pass only viable arguments), the rest of the changes are mostly
212 signature and pass only viable arguments), the rest of the changes are mostly
213 type annotation, and a few compatibility issues with Python 3.13 that are
213 type annotation, and a few compatibility issues with Python 3.13 that are
214 getting addressed.
214 getting addressed.
215
215
216 Python 3.13 compatibility is still not complete (help welcomed).
216 Python 3.13 compatibility is still not complete (help welcomed).
217
217
218 As usual you can find the full list of PRs on GitHub under `the 8.20
218 As usual you can find the full list of PRs on GitHub under `the 8.20
219 <https://github.com/ipython/ipython/milestone/127?closed=1>`__ milestone.
219 <https://github.com/ipython/ipython/milestone/127?closed=1>`__ milestone.
220
220
221 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
221 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
222 work on IPython and related libraries.
222 work on IPython and related libraries.
223
223
224
224
225 .. _version 8.19:
225 .. _version 8.19:
226
226
227 IPython 8.19
227 IPython 8.19
228 ------------
228 ------------
229
229
230 New release of IPython a bit before the end of the month, and end of the year.
230 New release of IPython a bit before the end of the month, and end of the year.
231
231
232 Mostly cleanup and deprecation, due to upstream deprecation and removal.
232 Mostly cleanup and deprecation, due to upstream deprecation and removal.
233
233
234 Remove of Python 3.9 support
234 Remove of Python 3.9 support
235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
236
236
237 A bit later than originally plan, IPython 8.19 does not support Python 3.9
237 A bit later than originally plan, IPython 8.19 does not support Python 3.9
238 anymore, as well as the few conditional code that were executing only on Python
238 anymore, as well as the few conditional code that were executing only on Python
239 3.9. :ghpull:`14254`
239 3.9. :ghpull:`14254`
240
240
241 We used the opportunity to deprecate ``IPython.utils.tz`` :ghpull:`14256`, due
241 We used the opportunity to deprecate ``IPython.utils.tz`` :ghpull:`14256`, due
242 to upstream deprecation of some timezone utilities. It will be removed at a later
242 to upstream deprecation of some timezone utilities. It will be removed at a later
243 date.
243 date.
244
244
245 We now also run CI on Python 3.12 (what I likely should have done before), but
245 We now also run CI on Python 3.12 (what I likely should have done before), but
246 running on too many Python version uses a lot of CI time.
246 running on too many Python version uses a lot of CI time.
247
247
248 Absolute and relative Line Numbers in Prompts
248 Absolute and relative Line Numbers in Prompts
249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
250
250
251 Thanks to the contribution of ``cohml``, IPython CLI now support absolute and
251 Thanks to the contribution of ``cohml``, IPython CLI now support absolute and
252 relative line numbers in both vi and emacs prompt, use for example
252 relative line numbers in both vi and emacs prompt, use for example
253 ``c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '``
253 ``c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '``
254 configuration option to display both in a custom format.
254 configuration option to display both in a custom format.
255
255
256 Miscellaneous
256 Miscellaneous
257 ~~~~~~~~~~~~~
257 ~~~~~~~~~~~~~
258
258
259 In addition to various bugfixes, I unpinned pytest, let me know if there are any
259 In addition to various bugfixes, I unpinned pytest, let me know if there are any
260 issues and we'll re-pin.
260 issues and we'll re-pin.
261
261
262 See you in 2024
262 See you in 2024
263 ~~~~~~~~~~~~~~~
263 ~~~~~~~~~~~~~~~
264
264
265 As usual you can find the full list of PRs on GitHub under `the 8.19
265 As usual you can find the full list of PRs on GitHub under `the 8.19
266 <https://github.com/ipython/ipython/milestone/126?closed=1>`__ milestone.
266 <https://github.com/ipython/ipython/milestone/126?closed=1>`__ milestone.
267
267
268 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
268 Thanks 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 8.18:
271 .. _version 8.18:
272
272
273 IPython 8.18 and 8.18.1
273 IPython 8.18 and 8.18.1
274 -----------------------
274 -----------------------
275
275
276 8.18.1 is identical to 8.18 but pin ``prompt_toolkit`` to greater than ``3.0.41``
276 8.18.1 is identical to 8.18 but pin ``prompt_toolkit`` to greater than ``3.0.41``
277
277
278 Small release of IPython that fixes a small number of inconveniences.
278 Small release of IPython that fixes a small number of inconveniences.
279
279
280 - :ghpull:`14251` Fix a memory leak in qt event loop integration by setting
280 - :ghpull:`14251` Fix a memory leak in qt event loop integration by setting
281 the Loop parent to None.
281 the Loop parent to None.
282 - :ghpull:`14252` Pickleshare was made an optional dependency in 8.17, this
282 - :ghpull:`14252` Pickleshare was made an optional dependency in 8.17, this
283 leads to warnings in some installations when using modules completions. The
283 leads to warnings in some installations when using modules completions. The
284 warning has been silenced.
284 warning has been silenced.
285 - :ghpull:`14241` Update event loop code for compatibility with more recent
285 - :ghpull:`14241` Update event loop code for compatibility with more recent
286 ``prompt_toolkit`` due to deprecations in Python 3.12.
286 ``prompt_toolkit`` due to deprecations in Python 3.12.
287 - :ghpull:`14245` Fix doc example on Pygments styles
287 - :ghpull:`14245` Fix doc example on Pygments styles
288 - :ghpull:`14238` Remove dependency on app_nope, this is actually only a
288 - :ghpull:`14238` Remove dependency on app_nope, this is actually only a
289 dependency of IPykernel.
289 dependency of IPykernel.
290
290
291 As usual you can find the full list of PRs on GitHub under `the 8.18
291 As usual you can find the full list of PRs on GitHub under `the 8.18
292 <https://github.com/ipython/ipython/milestone/125?closed=1>`__ milestone.
292 <https://github.com/ipython/ipython/milestone/125?closed=1>`__ milestone.
293
293
294 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
294 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
295 work on IPython and related libraries.
295 work on IPython and related libraries.
296
296
297 .. _version 8.17.1:
297 .. _version 8.17.1:
298 .. _version 8.17:
298 .. _version 8.17:
299
299
300 IPython 8.17, 8.17.1
300 IPython 8.17, 8.17.1
301 --------------------
301 --------------------
302
302
303 Medium-sized release of IPython that includes some cleanup (backcall, python2 leftovers)
303 Medium-sized release of IPython that includes some cleanup (backcall, python2 leftovers)
304 and some refactoring improvements (typing, pathlib) and a fix on completion.
304 and some refactoring improvements (typing, pathlib) and a fix on completion.
305
305
306 - :ghpull:`14216` remove backcall dependency
306 - :ghpull:`14216` remove backcall dependency
307 - :ghpull:`14217` make pickleshare dependency optional
307 - :ghpull:`14217` make pickleshare dependency optional
308 - :ghpull:`14185` support completion based on type annotations of calls
308 - :ghpull:`14185` support completion based on type annotations of calls
309
309
310 Reverted in 8.17.1:
310 Reverted in 8.17.1:
311
311
312 - :ghpull:`14190` remove support for python 2 in lexers (reverted in 8.17.1 as it is imported by qtconsole/spyder)
312 - :ghpull:`14190` remove support for python 2 in lexers (reverted in 8.17.1 as it is imported by qtconsole/spyder)
313
313
314 Mamba and Micromamba magic
314 Mamba and Micromamba magic
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~
316
316
317 In addition to the conda command to manage conda environment, mamba and
317 In addition to the conda command to manage conda environment, mamba and
318 micromamba can now be used using the corresponding magic in IPython.
318 micromamba can now be used using the corresponding magic in IPython.
319 Since these commands are compatible with conda, they are following the
319 Since these commands are compatible with conda, they are following the
320 same logic.
320 same logic.
321
321
322 These two magic require to have the corresponding commands available
322 These two magic require to have the corresponding commands available
323 either in the conda environment or system wide.
323 either in the conda environment or system wide.
324
324
325 :ghpull:`14191`
325 :ghpull:`14191`
326
326
327 ----
327 ----
328
328
329 As usual you can find the full list of PRs on GitHub under `the 8.17
329 As usual you can find the full list of PRs on GitHub under `the 8.17
330 <https://github.com/ipython/ipython/milestone/123?closed=1>`__ milestone.
330 <https://github.com/ipython/ipython/milestone/123?closed=1>`__ milestone.
331
331
332 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
332 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
333 work on IPython and related libraries.
333 work on IPython and related libraries.
334
334
335 .. _version 8.16:
335 .. _version 8.16:
336 .. _version 8.16.1:
336 .. _version 8.16.1:
337
337
338 IPython 8.16, 8.16.1
338 IPython 8.16, 8.16.1
339 --------------------
339 --------------------
340
340
341 Small double release of IPython (with the 8.12.3 release notes just below).
341 Small double release of IPython (with the 8.12.3 release notes just below).
342 Mostly bug fixes and cleanups, and type annotations. Of interest for users:
342 Mostly bug fixes and cleanups, and type annotations. Of interest for users:
343
343
344 - :ghpull:`14153` Fix a bug of the new iPdb chained traceback where some
344 - :ghpull:`14153` Fix a bug of the new iPdb chained traceback where some
345 Exception would not have any traceback. (see upstream fix in CPython for more
345 Exception would not have any traceback. (see upstream fix in CPython for more
346 details).
346 details).
347 - :ghpull:`14168` Fix case with spurious message about event loops when using
347 - :ghpull:`14168` Fix case with spurious message about event loops when using
348 matplotlib.
348 matplotlib.
349
349
350 This PR is in 8.16.0 but reverted in 8.16.1, we'll rework the fix for 8.17
350 This PR is in 8.16.0 but reverted in 8.16.1, we'll rework the fix for 8.17
351
351
352 - :ghpull:`14163` Fix an error where semicolon would not suppress output.
352 - :ghpull:`14163` Fix an error where semicolon would not suppress output.
353
353
354 As usual you can find the full list of PRs on GitHub under `the 8.16
354 As usual you can find the full list of PRs on GitHub under `the 8.16
355 <https://github.com/ipython/ipython/milestone/121?closed=1>`__ and `8.16.1 milestone
355 <https://github.com/ipython/ipython/milestone/121?closed=1>`__ and `8.16.1 milestone
356 <https://github.com/ipython/ipython/milestone/124?closed=1>`__.
356 <https://github.com/ipython/ipython/milestone/124?closed=1>`__.
357
357
358 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
358 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
359 work on IPython and related libraries.
359 work on IPython and related libraries.
360
360
361 .. _version 8.12.3:
361 .. _version 8.12.3:
362
362
363 IPython 8.12.3
363 IPython 8.12.3
364 --------------
364 --------------
365
365
366 Tiny release of 8.12.3 that backport a small number of fixes for users still
366 Tiny release of 8.12.3 that backport a small number of fixes for users still
367 using Python 3.8.
367 using Python 3.8.
368
368
369 - :ghpull:`14080` add passthrough filter shortcuts
369 - :ghpull:`14080` add passthrough filter shortcuts
370 - :ghpull:`14169` Fix `InteractiveShellEmbed`
370 - :ghpull:`14169` Fix `InteractiveShellEmbed`
371
371
372 .. _version 8.15:
372 .. _version 8.15:
373
373
374 IPython 8.15
374 IPython 8.15
375 ------------
375 ------------
376
376
377 Medium release of IPython after a couple of month hiatus, and a bit
377 Medium release of IPython after a couple of month hiatus, and a bit
378 off-schedule.
378 off-schedule.
379
379
380 Among other, IPython 8.15:
380 Among other, IPython 8.15:
381
381
382 - Improve compatibility with future version of Python 3.12/3.13
382 - Improve compatibility with future version of Python 3.12/3.13
383 :ghpull:`14107`, :ghpull:`14139`,
383 :ghpull:`14107`, :ghpull:`14139`,
384 - Improve support for ``ExceptionGroups``, :ghpull:`14108`
384 - Improve support for ``ExceptionGroups``, :ghpull:`14108`
385 - Fix hangs in ``%gui osx``, :ghpull:`14125`
385 - Fix hangs in ``%gui osx``, :ghpull:`14125`
386 - Fix memory lead with ``%reset``, :ghpull:`14133`
386 - Fix memory lead with ``%reset``, :ghpull:`14133`
387 - Unstable config option to modify traceback highlighting that is sometime hard
387 - Unstable config option to modify traceback highlighting that is sometime hard
388 to read :ghpull:`14138`
388 to read :ghpull:`14138`
389 - Support ``.`` in ``ipdb`` as an argument to the ``list`` command
389 - Support ``.`` in ``ipdb`` as an argument to the ``list`` command
390 :ghpull:`14121`
390 :ghpull:`14121`
391 - Workroud ``parso`` showing warning message when the default logger level is
391 - Workroud ``parso`` showing warning message when the default logger level is
392 changed :ghpull:`14119`
392 changed :ghpull:`14119`
393 - Fix multiple issues with matplotlib interactive mode, qt5/qt6 :ghpull:`14128`
393 - Fix multiple issues with matplotlib interactive mode, qt5/qt6 :ghpull:`14128`
394
394
395 Support for PEP-678 Exception Notes
395 Support for PEP-678 Exception Notes
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397
397
398 Ultratb now shows :pep:`678` notes, improving your debugging experience on
398 Ultratb now shows :pep:`678` notes, improving your debugging experience on
399 Python 3.11+ or with libraries such as Pytest and Hypothesis.
399 Python 3.11+ or with libraries such as Pytest and Hypothesis.
400
400
401 Native fallback for displaying ExceptionGroup
401 Native fallback for displaying ExceptionGroup
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403 ExceptionGroups are now displayed with ``traceback.print_exc``, as a temporary fix until UltraTB properly supports displaying child exceptions.
403 ExceptionGroups are now displayed with ``traceback.print_exc``, as a temporary fix until UltraTB properly supports displaying child exceptions.
404
404
405
405
406 We have two larger features:
406 We have two larger features:
407
407
408 AST-based macros
408 AST-based macros
409 ~~~~~~~~~~~~~~~~
409 ~~~~~~~~~~~~~~~~
410
410
411 :ghpull:`14100` introduce a new and efficient way to modify each execution block
411 :ghpull:`14100` introduce a new and efficient way to modify each execution block
412 (cell) using an template-ast-based transform. Unlike IPython pre and post code
412 (cell) using an template-ast-based transform. Unlike IPython pre and post code
413 execution hooks, this actually transform the code that is execute with as
413 execution hooks, this actually transform the code that is execute with as
414 minimal as possible overhead. While it was already technically possible to
414 minimal as possible overhead. While it was already technically possible to
415 register ast transformers for IPython this was far from evident.
415 register ast transformers for IPython this was far from evident.
416
416
417 This should make it trivial to hook into IPython to implement custom hooks, that
417 This should make it trivial to hook into IPython to implement custom hooks, that
418 for example time or profile your code, catch exceptions to provide error
418 for example time or profile your code, catch exceptions to provide error
419 messages for students or do any other kind of transformations.
419 messages for students or do any other kind of transformations.
420
420
421 In addition to programmatic API there is also a magic to quickly register
421 In addition to programmatic API there is also a magic to quickly register
422 hooks::
422 hooks::
423
423
424 In [1]: %%code_wrap before_after
424 In [1]: %%code_wrap before_after
425 ...: print('before')
425 ...: print('before')
426 ...: __code__
426 ...: __code__
427 ...: print('after')
427 ...: print('after')
428 ...: __ret__
428 ...: __ret__
429
429
430 This mean that for any subsequent execution code will be executed.
430 This mean that for any subsequent execution code will be executed.
431 You can modify the above to print the date, compute the execution time,
431 You can modify the above to print the date, compute the execution time,
432 retry the code in a for loop....
432 retry the code in a for loop....
433
433
434
434
435 Allow IPdb/Pdb to move between chained exceptions
435 Allow IPdb/Pdb to move between chained exceptions
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
437
437
438 The main change is the addition of the ability to move between chained
438 The main change is the addition of the ability to move between chained
439 exceptions when using IPdb, this feature was also contributed to upstream Pdb
439 exceptions when using IPdb, this feature was also contributed to upstream Pdb
440 and is thus native to CPython in Python 3.13+ Though ipdb should support this
440 and is thus native to CPython in Python 3.13+ Though ipdb should support this
441 feature in older version of Python. I invite you to look at the `CPython changes
441 feature in older version of Python. I invite you to look at the `CPython changes
442 and docs <https://github.com/python/cpython/pull/106676>`__ for more details.
442 and docs <https://github.com/python/cpython/pull/106676>`__ for more details.
443
443
444 In short, once in post-mortem debugger (``%debug``), you can use the ipdb
444 In short, once in post-mortem debugger (``%debug``), you can use the ipdb
445 ``exceptions`` command to switch exceptions, for example:
445 ``exceptions`` command to switch exceptions, for example:
446
446
447 .. code-block:: ipython
447 .. code-block:: ipython
448
448
449 In [1]: def foo(x):
449 In [1]: def foo(x):
450 ...: try:
450 ...: try:
451 ...: bar(x)
451 ...: bar(x)
452 ...: except Exception as e:
452 ...: except Exception as e:
453 ...: raise ValueError("foo (): bar failed") from e
453 ...: raise ValueError("foo (): bar failed") from e
454 ...:
454 ...:
455 ...: def bar(x):
455 ...: def bar(x):
456 ...: 1 / X
456 ...: 1 / X
457 ...:
457 ...:
458
458
459 In [2]: foo(0)
459 In [2]: foo(0)
460 ---------------------------------------------------------------------------
460 ---------------------------------------------------------------------------
461 NameError Traceback (most recent call last)
461 NameError Traceback (most recent call last)
462 Cell In[1], line 3, in foo(x)
462 Cell In[1], line 3, in foo(x)
463 2 try:
463 2 try:
464 ----> 3 bar(x)
464 ----> 3 bar(x)
465 4 except Exception as e:
465 4 except Exception as e:
466
466
467 Cell In[1], line 9, in bar(x)
467 Cell In[1], line 9, in bar(x)
468 8 def bar(x):
468 8 def bar(x):
469 ----> 9 1 / X
469 ----> 9 1 / X
470
470
471 NameError: name 'X' is not defined
471 NameError: name 'X' is not defined
472
472
473 The above exception was the direct cause of the following exception:
473 The above exception was the direct cause of the following exception:
474
474
475 ValueError Traceback (most recent call last)
475 ValueError Traceback (most recent call last)
476 Cell In[2], line 1
476 Cell In[2], line 1
477 ----> 1 foo(0)
477 ----> 1 foo(0)
478
478
479 Cell In[1], line 5, in foo(x)
479 Cell In[1], line 5, in foo(x)
480 3 bar(x)
480 3 bar(x)
481 4 except Exception as e:
481 4 except Exception as e:
482 ----> 5 raise ValueError("foo (): bar failed") from e
482 ----> 5 raise ValueError("foo (): bar failed") from e
483
483
484 ValueError: foo (): bar failed
484 ValueError: foo (): bar failed
485
485
486 In [3]: %debug
486 In [3]: %debug
487 > <ipython-input-1-b0bbdc271ffb>(5)foo()
487 > <ipython-input-1-b0bbdc271ffb>(5)foo()
488 3 bar(x)
488 3 bar(x)
489 4 except Exception as e:
489 4 except Exception as e:
490 ----> 5 raise ValueError("foo (): bar failed") from e
490 ----> 5 raise ValueError("foo (): bar failed") from e
491
491
492 In previous ipdb you could not go into the bar error, now from within pdb you
492 In previous ipdb you could not go into the bar error, now from within pdb you
493 can use ``exceptions``:
493 can use ``exceptions``:
494
494
495 .. code-block:: ipython
495 .. code-block:: ipython
496
496
497 ipdb> exceptions
497 ipdb> exceptions
498 0 NameError("name 'X' is not defined")
498 0 NameError("name 'X' is not defined")
499 > 1 ValueError('foo (): bar failed')
499 > 1 ValueError('foo (): bar failed')
500
500
501 ipdb> exceptions 0
501 ipdb> exceptions 0
502 > <ipython-input-1-b0bbdc271ffb>(9)bar()
502 > <ipython-input-1-b0bbdc271ffb>(9)bar()
503 6
503 6
504 7
504 7
505 8 def bar(x):
505 8 def bar(x):
506 ----> 9 1 / X
506 ----> 9 1 / X
507 10
507 10
508
508
509 ipdb>
509 ipdb>
510
510
511 In particular I want to thank the `D.E. Shaw group <https://www.deshaw.com/>`__
511 In particular I want to thank the `D.E. Shaw group <https://www.deshaw.com/>`__
512 for suggesting and funding the two largest feature as well as many bug fixes of
512 for suggesting and funding the two largest feature as well as many bug fixes of
513 this release.
513 this release.
514
514
515 As usual you can find the full list of PRs on GitHub under `the 8.15 milestone
515 As usual you can find the full list of PRs on GitHub under `the 8.15 milestone
516 <https://github.com/ipython/ipython/milestone/120?closed=1>`__.
516 <https://github.com/ipython/ipython/milestone/120?closed=1>`__.
517
517
518
518
519
519
520 .. _version 8.14:
520 .. _version 8.14:
521
521
522 IPython 8.14
522 IPython 8.14
523 ------------
523 ------------
524
524
525 Small release of IPython.
525 Small release of IPython.
526
526
527 - :ghpull:`14080` fixes some shortcuts issues.
527 - :ghpull:`14080` fixes some shortcuts issues.
528 - :ghpull:`14056` Add option to ``%autoreload`` to hide errors when reloading code. This will be the default for spyder
528 - :ghpull:`14056` Add option to ``%autoreload`` to hide errors when reloading code. This will be the default for spyder
529 user is my understanding.
529 user is my understanding.
530 - :ghpull:`14039` (and :ghpull:`14040`) to show exception notes in tracebacks.
530 - :ghpull:`14039` (and :ghpull:`14040`) to show exception notes in tracebacks.
531
531
532 - :ghpull:`14076` Add option to EventManager to prevent printing
532 - :ghpull:`14076` Add option to EventManager to prevent printing
533
533
534
534
535 SPEC 0 and SPEC 4
535 SPEC 0 and SPEC 4
536 ~~~~~~~~~~~~~~~~~
536 ~~~~~~~~~~~~~~~~~
537
537
538 You've heard about the NEPs, (NumPy enhancement Proposal), having a NEP for something non-numpy specific was sometime confusing.
538 You've heard about the NEPs, (NumPy enhancement Proposal), having a NEP for something non-numpy specific was sometime confusing.
539 Long live the `SPECs <https://scientific-python.org/specs/>`_.
539 Long live the `SPECs <https://scientific-python.org/specs/>`_.
540
540
541 We are now trying to follow SPEC 0 (aka old NEP 29) for support of upstream libraries.
541 We are now trying to follow SPEC 0 (aka old NEP 29) for support of upstream libraries.
542
542
543 We also now try to follow SPEC 4 (test and publish nightly on a centralized nightly repository).
543 We also now try to follow SPEC 4 (test and publish nightly on a centralized nightly repository).
544 We encourage you to do so as well in order to report breakage, and contribute to the SPEC process !
544 We encourage you to do so as well in order to report breakage, and contribute to the SPEC process !
545
545
546
546
547 Python 3.12 compatibility ?
547 Python 3.12 compatibility ?
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
549
549
550 Python 3.12 changed its tokenizer to have better support for f-strings and allow arbitrary expression.
550 Python 3.12 changed its tokenizer to have better support for f-strings and allow arbitrary expression.
551 This is a great new feature and performance improvement in Python 3.12.
551 This is a great new feature and performance improvement in Python 3.12.
552
552
553 Unfortunately this means the new tokenizer does not support incomplete or invalid Python which will
553 Unfortunately this means the new tokenizer does not support incomplete or invalid Python which will
554 break many features of IPython. Thus compatibility of IPython with Python 3.12 is not guarantied.
554 break many features of IPython. Thus compatibility of IPython with Python 3.12 is not guarantied.
555 It is unclear to which extent IPython is affected, and whether we can/should try to still support magics, shell
555 It is unclear to which extent IPython is affected, and whether we can/should try to still support magics, shell
556 escape (``! ....``), ..., as well as how to do it if we can.
556 escape (``! ....``), ..., as well as how to do it if we can.
557
557
558 In addition even if we there is technical feasibility to do so, it is no clear we have the resources to do it.
558 In addition even if we there is technical feasibility to do so, it is no clear we have the resources to do it.
559 We are thus looking for your help if you can _test_ on Python 3.12 to see to which extent this affects users and which
559 We are thus looking for your help if you can _test_ on Python 3.12 to see to which extent this affects users and which
560 features are critical.
560 features are critical.
561
561
562 We are not going to pin IPython to Python ``<3.12`` as otherwise on install pip would downgrade/resolve to IPython 8.13,
562 We are not going to pin IPython to Python ``<3.12`` as otherwise on install pip would downgrade/resolve to IPython 8.13,
563 so if you plan to update to Python 3.12 after its release, we encourage for extra care.
563 so if you plan to update to Python 3.12 after its release, we encourage for extra care.
564
564
565
565
566 .. _version 8.13.1:
566 .. _version 8.13.1:
567 .. _version 8.13.2:
567 .. _version 8.13.2:
568 .. _version 8.12.2:
568 .. _version 8.12.2:
569
569
570 IPython 8.13.1, 8.13.2 and 8.12.2
570 IPython 8.13.1, 8.13.2 and 8.12.2
571 ---------------------------------
571 ---------------------------------
572
572
573 3 quick in succession patch release of IPython in addition to IPython 8.13.0
573 3 quick in succession patch release of IPython in addition to IPython 8.13.0
574 having been yanked.
574 having been yanked.
575
575
576 IPython 8.13.0 was improperly tagged as still compatible with Python 3.8, and
576 IPython 8.13.0 was improperly tagged as still compatible with Python 3.8, and
577 still had some mention of compatibility with 3.8. IPython 8.13.1 is identical to
577 still had some mention of compatibility with 3.8. IPython 8.13.1 is identical to
578 8.13 but with the exception of being correctly tagged. This release and yank was
578 8.13 but with the exception of being correctly tagged. This release and yank was
579 mostly done to fix CI.
579 mostly done to fix CI.
580
580
581 IPython 8.12.2 and 8.13.2 contain UI fixes, with respect to right arrow not
581 IPython 8.12.2 and 8.13.2 contain UI fixes, with respect to right arrow not
582 working in some case in the terminal, and 8.12.2 contain also a requested
582 working in some case in the terminal, and 8.12.2 contain also a requested
583 backport of :ghpull:`14029` (Allow safe access to the ``__getattribute__``
583 backport of :ghpull:`14029` (Allow safe access to the ``__getattribute__``
584 method of modules) for tab completion.
584 method of modules) for tab completion.
585
585
586 .. _version 8.13:
586 .. _version 8.13:
587
587
588 IPython 8.13
588 IPython 8.13
589 ------------
589 ------------
590
590
591 As usual for the end of the month, minor release of IPython. This release is
591 As usual for the end of the month, minor release of IPython. This release is
592 significant in that it not only has a number of bugfixes, but also drop support
592 significant in that it not only has a number of bugfixes, but also drop support
593 for Python 3.8 as per NEP 29 (:ghpull:`14023`).
593 for Python 3.8 as per NEP 29 (:ghpull:`14023`).
594
594
595 All the critical bugfixes have been backported onto the 8.12.1 release (see
595 All the critical bugfixes have been backported onto the 8.12.1 release (see
596 below). In addition to that went into 8.12.1 you'll find:
596 below). In addition to that went into 8.12.1 you'll find:
597
597
598 - Pretty representation for ``Counter`` has been fixed to match the Python one
598 - Pretty representation for ``Counter`` has been fixed to match the Python one
599 and be in decreasing order. :ghpull:`14032`
599 and be in decreasing order. :ghpull:`14032`
600 - Module completion is better when jedi is disabled :ghpull:`14029`.
600 - Module completion is better when jedi is disabled :ghpull:`14029`.
601 - Improvement of ``%%bash`` magic that would get stuck :ghpull:`14019`
601 - Improvement of ``%%bash`` magic that would get stuck :ghpull:`14019`
602
602
603
603
604 We hope you enjoy this release an will maybe see you at JupyterCon in less than
604 We hope you enjoy this release an will maybe see you at JupyterCon in less than
605 two weeks.
605 two weeks.
606
606
607 As usual you can find the full list of PRs on GitHub under `the 8.13 milestone
607 As usual you can find the full list of PRs on GitHub under `the 8.13 milestone
608 <https://github.com/ipython/ipython/milestone/115?closed=1>`__.
608 <https://github.com/ipython/ipython/milestone/115?closed=1>`__.
609
609
610 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
610 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
611 work on IPython and related libraries.
611 work on IPython and related libraries.
612
612
613
613
614 .. _version 8.12.1:
614 .. _version 8.12.1:
615
615
616 IPython 8.12.1
616 IPython 8.12.1
617 --------------
617 --------------
618
618
619 This is the twin release of IPython 8.13 that contain only critical UI and bug
619 This is the twin release of IPython 8.13 that contain only critical UI and bug
620 fixes. The next minor version of IPython has dropped support for Python 3.8 – as
620 fixes. The next minor version of IPython has dropped support for Python 3.8 – as
621 per Nep 29 and this IPython 8.12.x will now only receive bugfixes.
621 per Nep 29 and this IPython 8.12.x will now only receive bugfixes.
622
622
623
623
624 - :ghpull:`14004` Fix a bug introduced in IPython 8.12 that crash when
624 - :ghpull:`14004` Fix a bug introduced in IPython 8.12 that crash when
625 inspecting some docstrings.
625 inspecting some docstrings.
626 - :ghpull:`14010` Fix fast traceback code that was not working in some case.
626 - :ghpull:`14010` Fix fast traceback code that was not working in some case.
627 - :ghpull:`14014` Fix ``%page`` magic broken in some case.
627 - :ghpull:`14014` Fix ``%page`` magic broken in some case.
628 - :ghpull:`14026`, :ghpull:`14027` Tweak default shortcut with respect to
628 - :ghpull:`14026`, :ghpull:`14027` Tweak default shortcut with respect to
629 autosuggestions.
629 autosuggestions.
630 - :ghpull:`14033` add back the ability to use ``.get()`` on OInfo object for
630 - :ghpull:`14033` add back the ability to use ``.get()`` on OInfo object for
631 backward compatibility with h5py (this will be re-deprecated later, and h5py
631 backward compatibility with h5py (this will be re-deprecated later, and h5py
632 will also get a fix).
632 will also get a fix).
633
633
634 As usual you can find the full list of PRs on GitHub under `the 8.12.1 milestone
634 As usual you can find the full list of PRs on GitHub under `the 8.12.1 milestone
635 <https://github.com/ipython/ipython/milestone/116?closed=1>`__.
635 <https://github.com/ipython/ipython/milestone/116?closed=1>`__.
636
636
637 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
637 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
638 work on IPython and related libraries.
638 work on IPython and related libraries.
639
639
640 .. _version 8.12.0:
640 .. _version 8.12.0:
641
641
642 IPython 8.12
642 IPython 8.12
643 ------------
643 ------------
644
644
645 Hopefully slightly early release for IPython 8.12. Last Thursday of the month,
645 Hopefully slightly early release for IPython 8.12. Last Thursday of the month,
646 even if I guess it's likely already Friday somewhere in the pacific ocean.
646 even if I guess it's likely already Friday somewhere in the pacific ocean.
647
647
648 A number of PRs and bug fixes this month with close to 20 PRs merged !
648 A number of PRs and bug fixes this month with close to 20 PRs merged !
649
649
650
650
651 The IPython repo reached :ghpull:`14000` !! Actually the PR that create those exact release
651 The IPython repo reached :ghpull:`14000` !! Actually the PR that create those exact release
652 note is :ghpull:`14000`. Ok, more issues and PR is not always better, and I'd
652 note is :ghpull:`14000`. Ok, more issues and PR is not always better, and I'd
653 love to have more time to close issues and Pull Requests.
653 love to have more time to close issues and Pull Requests.
654
654
655 Let's note that in less than 2 month JupyterCon is back, in Paris please visit
655 Let's note that in less than 2 month JupyterCon is back, in Paris please visit
656 `jupytercon.com <https://jupytercon.com>`__, and looking forward to see you
656 `jupytercon.com <https://jupytercon.com>`__, and looking forward to see you
657 there.
657 there.
658
658
659 Packagers should take note that ``typing_extension`` is now a mandatory dependency
659 Packagers should take note that ``typing_extension`` is now a mandatory dependency
660 for Python versions ``<3.10``.
660 for Python versions ``<3.10``.
661
661
662
662
663
663
664 Let's note also that according to `NEP29
664 Let's note also that according to `NEP29
665 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, It is soon time to
665 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, It is soon time to
666 stop support for Python 3.8 that will be release more than 3 and 1/2 years ago::
666 stop support for Python 3.8 that will be release more than 3 and 1/2 years ago::
667
667
668 On Apr 14, 2023 drop support for Python 3.8 (initially released on Oct 14, 2019)
668 On Apr 14, 2023 drop support for Python 3.8 (initially released on Oct 14, 2019)
669
669
670 Thus I am likely to stop advertising support for Python 3.8 in the next
670 Thus I am likely to stop advertising support for Python 3.8 in the next
671 release at the end of April.
671 release at the end of April.
672
672
673
673
674 Here are some miscellaneous updates of interest:
674 Here are some miscellaneous updates of interest:
675
675
676 - :ghpull:`13957` brings updates to the Qt integration, particularly for Qt6.
676 - :ghpull:`13957` brings updates to the Qt integration, particularly for Qt6.
677 - :ghpull:`13960` fixes the %debug magic command to give access to the local
677 - :ghpull:`13960` fixes the %debug magic command to give access to the local
678 scope.
678 scope.
679 - :ghpull:`13964` fixes some crashes with the new fast traceback code. Note that
679 - :ghpull:`13964` fixes some crashes with the new fast traceback code. Note that
680 there are still some issues with the fast traceback code, and I a, likely
680 there are still some issues with the fast traceback code, and I a, likely
681 to fix and tweak behavior.
681 to fix and tweak behavior.
682 - :ghpull:`13973` We are slowly migrating IPython internals to use proper type
682 - :ghpull:`13973` We are slowly migrating IPython internals to use proper type
683 objects/dataclasses instead of dictionaries to allow static typing checks.
683 objects/dataclasses instead of dictionaries to allow static typing checks.
684 These are technically public API and could lead to breakage, so please let us
684 These are technically public API and could lead to breakage, so please let us
685 know if that's the case and I'll mitigate.
685 know if that's the case and I'll mitigate.
686 - :ghpull:`13990`, :ghpull:`13991`, :ghpull:`13994` all improve keybinding and
686 - :ghpull:`13990`, :ghpull:`13991`, :ghpull:`13994` all improve keybinding and
687 shortcut configurability.
687 shortcut configurability.
688
688
689 As usual you can find the full list of PRs on GitHub under `the 8.12 milestone
689 As usual you can find the full list of PRs on GitHub under `the 8.12 milestone
690 <https://github.com/ipython/ipython/milestone/114?closed=1>`__.
690 <https://github.com/ipython/ipython/milestone/114?closed=1>`__.
691
691
692 We want to thank the D.E. Shaw group for requesting and sponsoring the work on
692 We want to thank the D.E. Shaw group for requesting and sponsoring the work on
693 the following big feature. We had productive discussions on how to best expose
693 the following big feature. We had productive discussions on how to best expose
694 this feature
694 this feature
695
695
696 Dynamic documentation dispatch
696 Dynamic documentation dispatch
697 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
698
698
699 We are experimenting with dynamic documentation dispatch for object attribute.
699 We are experimenting with dynamic documentation dispatch for object attribute.
700 See :ghissue:`13860`. The goal is to allow object to define documentation for
700 See :ghissue:`13860`. The goal is to allow object to define documentation for
701 their attributes, properties, even when those are dynamically defined with
701 their attributes, properties, even when those are dynamically defined with
702 `__getattr__`.
702 `__getattr__`.
703
703
704 In particular when those objects are base types it can be useful to show the
704 In particular when those objects are base types it can be useful to show the
705 documentation
705 documentation
706
706
707
707
708 .. code-block:: ipython
708 .. code-block:: ipython
709
709
710
710
711 In [1]: class User:
711 In [1]: class User:
712 ...:
712 ...:
713 ...: __custom_documentations__ = {
713 ...: __custom_documentations__ = {
714 ...: "first": "The first name of the user.",
714 ...: "first": "The first name of the user.",
715 ...: "last": "The last name of the user.",
715 ...: "last": "The last name of the user.",
716 ...: }
716 ...: }
717 ...:
717 ...:
718 ...: first:str
718 ...: first:str
719 ...: last:str
719 ...: last:str
720 ...:
720 ...:
721 ...: def __init__(self, first, last):
721 ...: def __init__(self, first, last):
722 ...: self.first = first
722 ...: self.first = first
723 ...: self.last = last
723 ...: self.last = last
724 ...:
724 ...:
725 ...: @property
725 ...: @property
726 ...: def full(self):
726 ...: def full(self):
727 ...: """`self.first` and `self.last` joined by a space."""
727 ...: """`self.first` and `self.last` joined by a space."""
728 ...: return self.first + " " + self.last
728 ...: return self.first + " " + self.last
729 ...:
729 ...:
730 ...:
730 ...:
731 ...: user = Person('Jane', 'Doe')
731 ...: user = Person('Jane', 'Doe')
732
732
733 In [2]: user.first?
733 In [2]: user.first?
734 Type: str
734 Type: str
735 String form: Jane
735 String form: Jane
736 Length: 4
736 Length: 4
737 Docstring: the first name of a the person object, a str
737 Docstring: the first name of a the person object, a str
738 Class docstring:
738 Class docstring:
739 ....
739 ....
740
740
741 In [3]: user.last?
741 In [3]: user.last?
742 Type: str
742 Type: str
743 String form: Doe
743 String form: Doe
744 Length: 3
744 Length: 3
745 Docstring: the last name, also a str
745 Docstring: the last name, also a str
746 ...
746 ...
747
747
748
748
749 We can see here the symmetry with IPython looking for the docstring on the
749 We can see here the symmetry with IPython looking for the docstring on the
750 properties:
750 properties:
751
751
752 .. code-block:: ipython
752 .. code-block:: ipython
753
753
754
754
755 In [4]: user.full?
755 In [4]: user.full?
756 HERE
756 HERE
757 Type: property
757 Type: property
758 String form: <property object at 0x102bb15d0>
758 String form: <property object at 0x102bb15d0>
759 Docstring: first and last join by a space
759 Docstring: first and last join by a space
760
760
761
761
762 Note that while in the above example we use a static dictionary, libraries may
762 Note that while in the above example we use a static dictionary, libraries may
763 decide to use a custom object that define ``__getitem__``, we caution against
763 decide to use a custom object that define ``__getitem__``, we caution against
764 using objects that would trigger computation to show documentation, but it is
764 using objects that would trigger computation to show documentation, but it is
765 sometime preferable for highly dynamic code that for example export ans API as
765 sometime preferable for highly dynamic code that for example export ans API as
766 object.
766 object.
767
767
768
768
769
769
770 .. _version 8.11.0:
770 .. _version 8.11.0:
771
771
772 IPython 8.11
772 IPython 8.11
773 ------------
773 ------------
774
774
775 Back on almost regular monthly schedule for IPython with end-of-month
775 Back on almost regular monthly schedule for IPython with end-of-month
776 really-late-Friday release to make sure some bugs are properly fixed.
776 really-late-Friday release to make sure some bugs are properly fixed.
777 Small addition of with a few new features, bugfix and UX improvements.
777 Small addition of with a few new features, bugfix and UX improvements.
778
778
779 This is a non-exhaustive list, but among other you will find:
779 This is a non-exhaustive list, but among other you will find:
780
780
781 Faster Traceback Highlighting
781 Faster Traceback Highlighting
782 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
782 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
783
783
784 Resurrection of pre-IPython-8 traceback highlighting code.
784 Resurrection of pre-IPython-8 traceback highlighting code.
785
785
786 Really long and complicated files were slow to highlight in traceback with
786 Really long and complicated files were slow to highlight in traceback with
787 IPython 8 despite upstream improvement that make many case better. Therefore
787 IPython 8 despite upstream improvement that make many case better. Therefore
788 starting with IPython 8.11 when one of the highlighted file is more than 10 000
788 starting with IPython 8.11 when one of the highlighted file is more than 10 000
789 line long by default, we'll fallback to a faster path that does not have all the
789 line long by default, we'll fallback to a faster path that does not have all the
790 features of highlighting failing AST nodes.
790 features of highlighting failing AST nodes.
791
791
792 This can be configures by setting the value of
792 This can be configures by setting the value of
793 ``IPython.code.ultratb.FAST_THRESHOLD`` to an arbitrary low or large value.
793 ``IPython.code.ultratb.FAST_THRESHOLD`` to an arbitrary low or large value.
794
794
795
795
796 Autoreload verbosity
796 Autoreload verbosity
797 ~~~~~~~~~~~~~~~~~~~~
797 ~~~~~~~~~~~~~~~~~~~~
798
798
799 We introduce more descriptive names for the ``%autoreload`` parameter:
799 We introduce more descriptive names for the ``%autoreload`` parameter:
800
800
801 - ``%autoreload now`` (also ``%autoreload``) - perform autoreload immediately.
801 - ``%autoreload now`` (also ``%autoreload``) - perform autoreload immediately.
802 - ``%autoreload off`` (also ``%autoreload 0``) - turn off autoreload.
802 - ``%autoreload off`` (also ``%autoreload 0``) - turn off autoreload.
803 - ``%autoreload explicit`` (also ``%autoreload 1``) - turn on autoreload only for modules
803 - ``%autoreload explicit`` (also ``%autoreload 1``) - turn on autoreload only for modules
804 whitelisted by ``%aimport`` statements.
804 whitelisted by ``%aimport`` statements.
805 - ``%autoreload all`` (also ``%autoreload 2``) - turn on autoreload for all modules except those
805 - ``%autoreload all`` (also ``%autoreload 2``) - turn on autoreload for all modules except those
806 blacklisted by ``%aimport`` statements.
806 blacklisted by ``%aimport`` statements.
807 - ``%autoreload complete`` (also ``%autoreload 3``) - all the fatures of ``all`` but also adding new
807 - ``%autoreload complete`` (also ``%autoreload 3``) - all the fatures of ``all`` but also adding new
808 objects from the imported modules (see
808 objects from the imported modules (see
809 IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects).
809 IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects).
810
810
811 The original designations (e.g. "2") still work, and these new ones are case-insensitive.
811 The original designations (e.g. "2") still work, and these new ones are case-insensitive.
812
812
813 Additionally, the option ``--print`` or ``-p`` can be added to the line to print the names of
813 Additionally, the option ``--print`` or ``-p`` can be added to the line to print the names of
814 modules being reloaded. Similarly, ``--log`` or ``-l`` will output the names to the logger at INFO
814 modules being reloaded. Similarly, ``--log`` or ``-l`` will output the names to the logger at INFO
815 level. Both can be used simultaneously.
815 level. Both can be used simultaneously.
816
816
817 The parsing logic for ``%aimport`` is now improved such that modules can be whitelisted and
817 The parsing logic for ``%aimport`` is now improved such that modules can be whitelisted and
818 blacklisted in the same line, e.g. it's now possible to call ``%aimport os, -math`` to include
818 blacklisted in the same line, e.g. it's now possible to call ``%aimport os, -math`` to include
819 ``os`` for ``%autoreload explicit`` and exclude ``math`` for modes ``all`` and ``complete``.
819 ``os`` for ``%autoreload explicit`` and exclude ``math`` for modes ``all`` and ``complete``.
820
820
821 Terminal shortcuts customization
821 Terminal shortcuts customization
822 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
823
823
824 Previously modifying shortcuts was only possible by hooking into startup files
824 Previously modifying shortcuts was only possible by hooking into startup files
825 and practically limited to adding new shortcuts or removing all shortcuts bound
825 and practically limited to adding new shortcuts or removing all shortcuts bound
826 to a specific key. This release enables users to override existing terminal
826 to a specific key. This release enables users to override existing terminal
827 shortcuts, disable them or add new keybindings.
827 shortcuts, disable them or add new keybindings.
828
828
829 For example, to set the :kbd:`right` to accept a single character of auto-suggestion
829 For example, to set the :kbd:`right` to accept a single character of auto-suggestion
830 you could use::
830 you could use::
831
831
832 my_shortcuts = [
832 my_shortcuts = [
833 {
833 {
834 "command": "IPython:auto_suggest.accept_character",
834 "command": "IPython:auto_suggest.accept_character",
835 "new_keys": ["right"]
835 "new_keys": ["right"]
836 }
836 }
837 ]
837 ]
838 %config TerminalInteractiveShell.shortcuts = my_shortcuts
838 %config TerminalInteractiveShell.shortcuts = my_shortcuts
839
839
840 You can learn more in :std:configtrait:`TerminalInteractiveShell.shortcuts`
840 You can learn more in :std:configtrait:`TerminalInteractiveShell.shortcuts`
841 configuration reference.
841 configuration reference.
842
842
843 Miscellaneous
843 Miscellaneous
844 ~~~~~~~~~~~~~
844 ~~~~~~~~~~~~~
845
845
846 - ``%gui`` should now support PySide6. :ghpull:`13864`
846 - ``%gui`` should now support PySide6. :ghpull:`13864`
847 - Cli shortcuts can now be configured :ghpull:`13928`, see above.
847 - Cli shortcuts can now be configured :ghpull:`13928`, see above.
848 (note that there might be an issue with prompt_toolkit 3.0.37 and shortcut configuration).
848 (note that there might be an issue with prompt_toolkit 3.0.37 and shortcut configuration).
849
849
850 - Capture output should now respect ``;`` semicolon to suppress output.
850 - Capture output should now respect ``;`` semicolon to suppress output.
851 :ghpull:`13940`
851 :ghpull:`13940`
852 - Base64 encoded images (in jupyter frontend), will not have trailing newlines.
852 - Base64 encoded images (in jupyter frontend), will not have trailing newlines.
853 :ghpull:`13941`
853 :ghpull:`13941`
854
854
855 As usual you can find the full list of PRs on GitHub under `the 8.11 milestone
855 As usual you can find the full list of PRs on GitHub under `the 8.11 milestone
856 <https://github.com/ipython/ipython/milestone/113?closed=1>`__.
856 <https://github.com/ipython/ipython/milestone/113?closed=1>`__.
857
857
858 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
858 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
859 work on IPython and related libraries.
859 work on IPython and related libraries.
860
860
861 .. _version 8.10.0:
861 .. _version 8.10.0:
862
862
863 IPython 8.10
863 IPython 8.10
864 ------------
864 ------------
865
865
866 Out of schedule release of IPython with minor fixes to patch a potential CVE-2023-24816.
866 Out of schedule release of IPython with minor fixes to patch a potential CVE-2023-24816.
867 This is a really low severity CVE that you most likely are not affected by unless:
867 This is a really low severity CVE that you most likely are not affected by unless:
868
868
869 - You are on windows.
869 - You are on windows.
870 - You have a custom build of Python without ``_ctypes``
870 - You have a custom build of Python without ``_ctypes``
871 - You cd or start IPython or Jupyter in untrusted directory which names may be
871 - You cd or start IPython or Jupyter in untrusted directory which names may be
872 valid shell commands.
872 valid shell commands.
873
873
874 You can read more on `the advisory
874 You can read more on `the advisory
875 <https://github.com/ipython/ipython/security/advisories/GHSA-29gw-9793-fvw7>`__.
875 <https://github.com/ipython/ipython/security/advisories/GHSA-29gw-9793-fvw7>`__.
876
876
877 In addition to fixing this CVE we also fix a couple of outstanding bugs and issues.
877 In addition to fixing this CVE we also fix a couple of outstanding bugs and issues.
878
878
879 As usual you can find the full list of PRs on GitHub under `the 8.10 milestone
879 As usual you can find the full list of PRs on GitHub under `the 8.10 milestone
880 <https://github.com/ipython/ipython/milestone/112?closed=1>`__.
880 <https://github.com/ipython/ipython/milestone/112?closed=1>`__.
881
881
882 In Particular:
882 In Particular:
883
883
884 - bump minimum numpy to `>=1.21` version following NEP29. :ghpull:`13930`
884 - bump minimum numpy to `>=1.21` version following NEP29. :ghpull:`13930`
885 - fix for compatibility with MyPy 1.0. :ghpull:`13933`
885 - fix for compatibility with MyPy 1.0. :ghpull:`13933`
886 - fix nbgrader stalling when IPython's ``showtraceback`` function is
886 - fix nbgrader stalling when IPython's ``showtraceback`` function is
887 monkeypatched. :ghpull:`13934`
887 monkeypatched. :ghpull:`13934`
888
888
889
889
890
890
891 As this release also contains those minimal changes in addition to fixing the
891 As this release also contains those minimal changes in addition to fixing the
892 CVE I decided to bump the minor version anyway.
892 CVE I decided to bump the minor version anyway.
893
893
894 This will not affect the normal release schedule, so IPython 8.11 is due in
894 This will not affect the normal release schedule, so IPython 8.11 is due in
895 about 2 weeks.
895 about 2 weeks.
896
896
897 .. _version 8.9.0:
897 .. _version 8.9.0:
898
898
899 IPython 8.9.0
899 IPython 8.9.0
900 -------------
900 -------------
901
901
902 Second release of IPython in 2023, last Friday of the month, we are back on
902 Second release of IPython in 2023, last Friday of the month, we are back on
903 track. This is a small release with a few bug-fixes, and improvements, mostly
903 track. This is a small release with a few bug-fixes, and improvements, mostly
904 with respect to terminal shortcuts.
904 with respect to terminal shortcuts.
905
905
906
906
907 The biggest improvement for 8.9 is a drastic amelioration of the
907 The biggest improvement for 8.9 is a drastic amelioration of the
908 auto-suggestions sponsored by D.E. Shaw and implemented by the more and more
908 auto-suggestions sponsored by D.E. Shaw and implemented by the more and more
909 active contributor `@krassowski <https://github.com/krassowski>`.
909 active contributor `@krassowski <https://github.com/krassowski>`.
910
910
911 - ``right`` accepts a single character from suggestion
911 - ``right`` accepts a single character from suggestion
912 - ``ctrl+right`` accepts a semantic token (macos default shortcuts take
912 - ``ctrl+right`` accepts a semantic token (macos default shortcuts take
913 precedence and need to be disabled to make this work)
913 precedence and need to be disabled to make this work)
914 - ``backspace`` deletes a character and resumes hinting autosuggestions
914 - ``backspace`` deletes a character and resumes hinting autosuggestions
915 - ``ctrl-left`` accepts suggestion and moves cursor left one character.
915 - ``ctrl-left`` accepts suggestion and moves cursor left one character.
916 - ``backspace`` deletes a character and resumes hinting autosuggestions
916 - ``backspace`` deletes a character and resumes hinting autosuggestions
917 - ``down`` moves to suggestion to later in history when no lines are present below the cursors.
917 - ``down`` moves to suggestion to later in history when no lines are present below the cursors.
918 - ``up`` moves to suggestion from earlier in history when no lines are present above the cursor.
918 - ``up`` moves to suggestion from earlier in history when no lines are present above the cursor.
919
919
920 This is best described by the Gif posted by `@krassowski
920 This is best described by the Gif posted by `@krassowski
921 <https://github.com/krassowski>`, and in the PR itself :ghpull:`13888`.
921 <https://github.com/krassowski>`, and in the PR itself :ghpull:`13888`.
922
922
923 .. image:: ../_images/autosuggest.gif
923 .. image:: ../_images/autosuggest.gif
924
924
925 Please report any feedback in order for us to improve the user experience.
925 Please report any feedback in order for us to improve the user experience.
926 In particular we are also working on making the shortcuts configurable.
926 In particular we are also working on making the shortcuts configurable.
927
927
928 If you are interested in better terminal shortcuts, I also invite you to
928 If you are interested in better terminal shortcuts, I also invite you to
929 participate in issue `13879
929 participate in issue `13879
930 <https://github.com/ipython/ipython/issues/13879>`__.
930 <https://github.com/ipython/ipython/issues/13879>`__.
931
931
932
932
933 As we follow `NEP29
933 As we follow `NEP29
934 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, next version of
934 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, next version of
935 IPython will officially stop supporting numpy 1.20, and will stop supporting
935 IPython will officially stop supporting numpy 1.20, and will stop supporting
936 Python 3.8 after April release.
936 Python 3.8 after April release.
937
937
938 As usual you can find the full list of PRs on GitHub under `the 8.9 milestone
938 As usual you can find the full list of PRs on GitHub under `the 8.9 milestone
939 <https://github.com/ipython/ipython/milestone/111?closed=1>`__.
939 <https://github.com/ipython/ipython/milestone/111?closed=1>`__.
940
940
941
941
942 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
942 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
943 work on IPython and related libraries.
943 work on IPython and related libraries.
944
944
945 .. _version 8.8.0:
945 .. _version 8.8.0:
946
946
947 IPython 8.8.0
947 IPython 8.8.0
948 -------------
948 -------------
949
949
950 First release of IPython in 2023 as there was no release at the end of
950 First release of IPython in 2023 as there was no release at the end of
951 December.
951 December.
952
952
953 This is an unusually big release (relatively speaking) with more than 15 Pull
953 This is an unusually big release (relatively speaking) with more than 15 Pull
954 Requests merged.
954 Requests merged.
955
955
956 Of particular interest are:
956 Of particular interest are:
957
957
958 - :ghpull:`13852` that replaces the greedy completer and improves
958 - :ghpull:`13852` that replaces the greedy completer and improves
959 completion, in particular for dictionary keys.
959 completion, in particular for dictionary keys.
960 - :ghpull:`13858` that adds ``py.typed`` to ``setup.cfg`` to make sure it is
960 - :ghpull:`13858` that adds ``py.typed`` to ``setup.cfg`` to make sure it is
961 bundled in wheels.
961 bundled in wheels.
962 - :ghpull:`13869` that implements tab completions for IPython options in the
962 - :ghpull:`13869` that implements tab completions for IPython options in the
963 shell when using `argcomplete <https://github.com/kislyuk/argcomplete>`. I
963 shell when using `argcomplete <https://github.com/kislyuk/argcomplete>`. I
964 believe this also needs a recent version of Traitlets.
964 believe this also needs a recent version of Traitlets.
965 - :ghpull:`13865` makes the ``inspector`` class of `InteractiveShell`
965 - :ghpull:`13865` makes the ``inspector`` class of `InteractiveShell`
966 configurable.
966 configurable.
967 - :ghpull:`13880` that removes minor-version entrypoints as the minor version
967 - :ghpull:`13880` that removes minor-version entrypoints as the minor version
968 entry points that would be included in the wheel would be the one of the
968 entry points that would be included in the wheel would be the one of the
969 Python version that was used to build the ``whl`` file.
969 Python version that was used to build the ``whl`` file.
970
970
971 In no particular order, the rest of the changes update the test suite to be
971 In no particular order, the rest of the changes update the test suite to be
972 compatible with Pygments 2.14, various docfixes, testing on more recent python
972 compatible with Pygments 2.14, various docfixes, testing on more recent python
973 versions and various updates.
973 versions and various updates.
974
974
975 As usual you can find the full list of PRs on GitHub under `the 8.8 milestone
975 As usual you can find the full list of PRs on GitHub under `the 8.8 milestone
976 <https://github.com/ipython/ipython/milestone/110>`__.
976 <https://github.com/ipython/ipython/milestone/110>`__.
977
977
978 Many thanks to @krassowski for the many PRs and @jasongrout for reviewing and
978 Many thanks to @krassowski for the many PRs and @jasongrout for reviewing and
979 merging contributions.
979 merging contributions.
980
980
981 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
981 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
982 work on IPython and related libraries.
982 work on IPython and related libraries.
983
983
984 .. _version 8.7.0:
984 .. _version 8.7.0:
985
985
986 IPython 8.7.0
986 IPython 8.7.0
987 -------------
987 -------------
988
988
989
989
990 Small release of IPython with a couple of bug fixes and new features for this
990 Small release of IPython with a couple of bug fixes and new features for this
991 month. Next month is the end of year, it is unclear if there will be a release
991 month. Next month is the end of year, it is unclear if there will be a release
992 close to the new year's eve, or if the next release will be at the end of January.
992 close to the new year's eve, or if the next release will be at the end of January.
993
993
994 Here are a few of the relevant fixes,
994 Here are a few of the relevant fixes,
995 as usual you can find the full list of PRs on GitHub under `the 8.7 milestone
995 as usual you can find the full list of PRs on GitHub under `the 8.7 milestone
996 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.7>`__.
996 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.7>`__.
997
997
998
998
999 - :ghpull:`13834` bump the minimum prompt toolkit to 3.0.11.
999 - :ghpull:`13834` bump the minimum prompt toolkit to 3.0.11.
1000 - IPython shipped with the ``py.typed`` marker now, and we are progressively
1000 - IPython shipped with the ``py.typed`` marker now, and we are progressively
1001 adding more types. :ghpull:`13831`
1001 adding more types. :ghpull:`13831`
1002 - :ghpull:`13817` add configuration of code blacks formatting.
1002 - :ghpull:`13817` add configuration of code blacks formatting.
1003
1003
1004
1004
1005 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1005 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1006 work on IPython and related libraries.
1006 work on IPython and related libraries.
1007
1007
1008
1008
1009 .. _version 8.6.0:
1009 .. _version 8.6.0:
1010
1010
1011 IPython 8.6.0
1011 IPython 8.6.0
1012 -------------
1012 -------------
1013
1013
1014 Back to a more regular release schedule (at least I try), as Friday is
1014 Back to a more regular release schedule (at least I try), as Friday is
1015 already over by more than 24h hours. This is a slightly bigger release with a
1015 already over by more than 24h hours. This is a slightly bigger release with a
1016 few new features that contain no less than 25 PRs.
1016 few new features that contain no less than 25 PRs.
1017
1017
1018 We'll notably found a couple of non negligible changes:
1018 We'll notably found a couple of non negligible changes:
1019
1019
1020 The ``install_ext`` and related functions have been removed after being
1020 The ``install_ext`` and related functions have been removed after being
1021 deprecated for years. You can use pip to install extensions. ``pip`` did not
1021 deprecated for years. You can use pip to install extensions. ``pip`` did not
1022 exist when ``install_ext`` was introduced. You can still load local extensions
1022 exist when ``install_ext`` was introduced. You can still load local extensions
1023 without installing them. Just set your ``sys.path`` for example. :ghpull:`13744`
1023 without installing them. Just set your ``sys.path`` for example. :ghpull:`13744`
1024
1024
1025 IPython now has extra entry points that use the major *and minor* version of
1025 IPython now has extra entry points that use the major *and minor* version of
1026 python. For some of you this means that you can do a quick ``ipython3.10`` to
1026 python. For some of you this means that you can do a quick ``ipython3.10`` to
1027 launch IPython from the Python 3.10 interpreter, while still using Python 3.11
1027 launch IPython from the Python 3.10 interpreter, while still using Python 3.11
1028 as your main Python. :ghpull:`13743`
1028 as your main Python. :ghpull:`13743`
1029
1029
1030 The completer matcher API has been improved. See :ghpull:`13745`. This should
1030 The completer matcher API has been improved. See :ghpull:`13745`. This should
1031 improve the type inference and improve dict keys completions in many use case.
1031 improve the type inference and improve dict keys completions in many use case.
1032 Thanks ``@krassowski`` for all the work, and the D.E. Shaw group for sponsoring
1032 Thanks ``@krassowski`` for all the work, and the D.E. Shaw group for sponsoring
1033 it.
1033 it.
1034
1034
1035 The color of error nodes in tracebacks can now be customized. See
1035 The color of error nodes in tracebacks can now be customized. See
1036 :ghpull:`13756`. This is a private attribute until someone finds the time to
1036 :ghpull:`13756`. This is a private attribute until someone finds the time to
1037 properly add a configuration option. Note that with Python 3.11 that also shows
1037 properly add a configuration option. Note that with Python 3.11 that also shows
1038 the relevant nodes in traceback, it would be good to leverage this information
1038 the relevant nodes in traceback, it would be good to leverage this information
1039 (plus the "did you mean" info added on attribute errors). But that's likely work
1039 (plus the "did you mean" info added on attribute errors). But that's likely work
1040 I won't have time to do before long, so contributions welcome.
1040 I won't have time to do before long, so contributions welcome.
1041
1041
1042 As we follow NEP 29, we removed support for numpy 1.19 :ghpull:`13760`.
1042 As we follow NEP 29, we removed support for numpy 1.19 :ghpull:`13760`.
1043
1043
1044
1044
1045 The ``open()`` function present in the user namespace by default will now refuse
1045 The ``open()`` function present in the user namespace by default will now refuse
1046 to open the file descriptors 0,1,2 (stdin, out, err), to avoid crashing IPython.
1046 to open the file descriptors 0,1,2 (stdin, out, err), to avoid crashing IPython.
1047 This mostly occurs in teaching context when incorrect values get passed around.
1047 This mostly occurs in teaching context when incorrect values get passed around.
1048
1048
1049
1049
1050 The ``?``, ``??``, and corresponding ``pinfo``, ``pinfo2`` magics can now find
1050 The ``?``, ``??``, and corresponding ``pinfo``, ``pinfo2`` magics can now find
1051 objects inside arrays. That is to say, the following now works::
1051 objects inside arrays. That is to say, the following now works::
1052
1052
1053
1053
1054 >>> def my_func(*arg, **kwargs):pass
1054 >>> def my_func(*arg, **kwargs):pass
1055 >>> container = [my_func]
1055 >>> container = [my_func]
1056 >>> container[0]?
1056 >>> container[0]?
1057
1057
1058
1058
1059 If ``container`` define a custom ``getitem``, this __will__ trigger the custom
1059 If ``container`` define a custom ``getitem``, this __will__ trigger the custom
1060 method. So don't put side effects in your ``getitems``. Thanks to the D.E. Shaw
1060 method. So don't put side effects in your ``getitems``. Thanks to the D.E. Shaw
1061 group for the request and sponsoring the work.
1061 group for the request and sponsoring the work.
1062
1062
1063
1063
1064 As usual you can find the full list of PRs on GitHub under `the 8.6 milestone
1064 As usual you can find the full list of PRs on GitHub under `the 8.6 milestone
1065 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.6>`__.
1065 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.6>`__.
1066
1066
1067 Thanks to all hacktoberfest contributors, please contribute to
1067 Thanks to all hacktoberfest contributors, please contribute to
1068 `closember.org <https://closember.org/>`__.
1068 `closember.org <https://closember.org/>`__.
1069
1069
1070 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1070 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1071 work on IPython and related libraries.
1071 work on IPython and related libraries.
1072
1072
1073 .. _version 8.5.0:
1073 .. _version 8.5.0:
1074
1074
1075 IPython 8.5.0
1075 IPython 8.5.0
1076 -------------
1076 -------------
1077
1077
1078 First release since a couple of month due to various reasons and timing preventing
1078 First release since a couple of month due to various reasons and timing preventing
1079 me for sticking to the usual monthly release the last Friday of each month. This
1079 me for sticking to the usual monthly release the last Friday of each month. This
1080 is of non negligible size as it has more than two dozen PRs with various fixes
1080 is of non negligible size as it has more than two dozen PRs with various fixes
1081 an bug fixes.
1081 an bug fixes.
1082
1082
1083 Many thanks to everybody who contributed PRs for your patience in review and
1083 Many thanks to everybody who contributed PRs for your patience in review and
1084 merges.
1084 merges.
1085
1085
1086 Here is a non-exhaustive list of changes that have been implemented for IPython
1086 Here is a non-exhaustive list of changes that have been implemented for IPython
1087 8.5.0. As usual you can find the full list of issues and PRs tagged with `the
1087 8.5.0. As usual you can find the full list of issues and PRs tagged with `the
1088 8.5 milestone
1088 8.5 milestone
1089 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A8.5+>`__.
1089 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A8.5+>`__.
1090
1090
1091 - Added a shortcut for accepting auto suggestion. The End key shortcut for
1091 - Added a shortcut for accepting auto suggestion. The End key shortcut for
1092 accepting auto-suggestion This binding works in Vi mode too, provided
1092 accepting auto-suggestion This binding works in Vi mode too, provided
1093 ``TerminalInteractiveShell.emacs_bindings_in_vi_insert_mode`` is set to be
1093 ``TerminalInteractiveShell.emacs_bindings_in_vi_insert_mode`` is set to be
1094 ``True`` :ghpull:`13566`.
1094 ``True`` :ghpull:`13566`.
1095
1095
1096 - No popup in window for latex generation when generating latex (e.g. via
1096 - No popup in window for latex generation when generating latex (e.g. via
1097 `_latex_repr_`) no popup window is shows under Windows. :ghpull:`13679`
1097 `_latex_repr_`) no popup window is shows under Windows. :ghpull:`13679`
1098
1098
1099 - Fixed error raised when attempting to tab-complete an input string with
1099 - Fixed error raised when attempting to tab-complete an input string with
1100 consecutive periods or forward slashes (such as "file:///var/log/...").
1100 consecutive periods or forward slashes (such as "file:///var/log/...").
1101 :ghpull:`13675`
1101 :ghpull:`13675`
1102
1102
1103 - Relative filenames in Latex rendering :
1103 - Relative filenames in Latex rendering :
1104 The `latex_to_png_dvipng` command internally generates input and output file
1104 The `latex_to_png_dvipng` command internally generates input and output file
1105 arguments to `latex` and `dvipis`. These arguments are now generated as
1105 arguments to `latex` and `dvipis`. These arguments are now generated as
1106 relative files to the current working directory instead of absolute file
1106 relative files to the current working directory instead of absolute file
1107 paths. This solves a problem where the current working directory contains
1107 paths. This solves a problem where the current working directory contains
1108 characters that are not handled properly by `latex` and `dvips`. There are
1108 characters that are not handled properly by `latex` and `dvips`. There are
1109 no changes to the user API. :ghpull:`13680`
1109 no changes to the user API. :ghpull:`13680`
1110
1110
1111 - Stripping decorators bug: Fixed bug which meant that ipython code blocks in
1111 - Stripping decorators bug: Fixed bug which meant that ipython code blocks in
1112 restructured text documents executed with the ipython-sphinx extension
1112 restructured text documents executed with the ipython-sphinx extension
1113 skipped any lines of code containing python decorators. :ghpull:`13612`
1113 skipped any lines of code containing python decorators. :ghpull:`13612`
1114
1114
1115 - Allow some modules with frozen dataclasses to be reloaded. :ghpull:`13732`
1115 - Allow some modules with frozen dataclasses to be reloaded. :ghpull:`13732`
1116 - Fix paste magic on wayland. :ghpull:`13671`
1116 - Fix paste magic on wayland. :ghpull:`13671`
1117 - show maxlen in deque's repr. :ghpull:`13648`
1117 - show maxlen in deque's repr. :ghpull:`13648`
1118
1118
1119 Restore line numbers for Input
1119 Restore line numbers for Input
1120 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1120 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1121
1121
1122 Line number information in tracebacks from input are restored.
1122 Line number information in tracebacks from input are restored.
1123 Line numbers from input were removed during the transition to v8 enhanced traceback reporting.
1123 Line numbers from input were removed during the transition to v8 enhanced traceback reporting.
1124
1124
1125 So, instead of::
1125 So, instead of::
1126
1126
1127 ---------------------------------------------------------------------------
1127 ---------------------------------------------------------------------------
1128 ZeroDivisionError Traceback (most recent call last)
1128 ZeroDivisionError Traceback (most recent call last)
1129 Input In [3], in <cell line: 1>()
1129 Input In [3], in <cell line: 1>()
1130 ----> 1 myfunc(2)
1130 ----> 1 myfunc(2)
1131
1131
1132 Input In [2], in myfunc(z)
1132 Input In [2], in myfunc(z)
1133 1 def myfunc(z):
1133 1 def myfunc(z):
1134 ----> 2 foo.boo(z-1)
1134 ----> 2 foo.boo(z-1)
1135
1135
1136 File ~/code/python/ipython/foo.py:3, in boo(x)
1136 File ~/code/python/ipython/foo.py:3, in boo(x)
1137 2 def boo(x):
1137 2 def boo(x):
1138 ----> 3 return 1/(1-x)
1138 ----> 3 return 1/(1-x)
1139
1139
1140 ZeroDivisionError: division by zero
1140 ZeroDivisionError: division by zero
1141
1141
1142 The error traceback now looks like::
1142 The error traceback now looks like::
1143
1143
1144 ---------------------------------------------------------------------------
1144 ---------------------------------------------------------------------------
1145 ZeroDivisionError Traceback (most recent call last)
1145 ZeroDivisionError Traceback (most recent call last)
1146 Cell In [3], line 1
1146 Cell In [3], line 1
1147 ----> 1 myfunc(2)
1147 ----> 1 myfunc(2)
1148
1148
1149 Cell In [2], line 2, in myfunc(z)
1149 Cell In [2], line 2, in myfunc(z)
1150 1 def myfunc(z):
1150 1 def myfunc(z):
1151 ----> 2 foo.boo(z-1)
1151 ----> 2 foo.boo(z-1)
1152
1152
1153 File ~/code/python/ipython/foo.py:3, in boo(x)
1153 File ~/code/python/ipython/foo.py:3, in boo(x)
1154 2 def boo(x):
1154 2 def boo(x):
1155 ----> 3 return 1/(1-x)
1155 ----> 3 return 1/(1-x)
1156
1156
1157 ZeroDivisionError: division by zero
1157 ZeroDivisionError: division by zero
1158
1158
1159 or, with xmode=Plain::
1159 or, with xmode=Plain::
1160
1160
1161 Traceback (most recent call last):
1161 Traceback (most recent call last):
1162 Cell In [12], line 1
1162 Cell In [12], line 1
1163 myfunc(2)
1163 myfunc(2)
1164 Cell In [6], line 2 in myfunc
1164 Cell In [6], line 2 in myfunc
1165 foo.boo(z-1)
1165 foo.boo(z-1)
1166 File ~/code/python/ipython/foo.py:3 in boo
1166 File ~/code/python/ipython/foo.py:3 in boo
1167 return 1/(1-x)
1167 return 1/(1-x)
1168 ZeroDivisionError: division by zero
1168 ZeroDivisionError: division by zero
1169
1169
1170 :ghpull:`13560`
1170 :ghpull:`13560`
1171
1171
1172 New setting to silence warning if working inside a virtual environment
1172 New setting to silence warning if working inside a virtual environment
1173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1174
1174
1175 Previously, when starting IPython in a virtual environment without IPython installed (so IPython from the global environment is used), the following warning was printed:
1175 Previously, when starting IPython in a virtual environment without IPython installed (so IPython from the global environment is used), the following warning was printed:
1176
1176
1177 Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
1177 Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
1178
1178
1179 This warning can be permanently silenced by setting ``c.InteractiveShell.warn_venv`` to ``False`` (the default is ``True``).
1179 This warning can be permanently silenced by setting ``c.InteractiveShell.warn_venv`` to ``False`` (the default is ``True``).
1180
1180
1181 :ghpull:`13706`
1181 :ghpull:`13706`
1182
1182
1183 -------
1183 -------
1184
1184
1185 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1185 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1186 work on IPython and related libraries.
1186 work on IPython and related libraries.
1187
1187
1188
1188
1189 .. _version 8.4.0:
1189 .. _version 8.4.0:
1190
1190
1191 IPython 8.4.0
1191 IPython 8.4.0
1192 -------------
1192 -------------
1193
1193
1194 As for 7.34, this version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
1194 As for 7.34, this version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
1195 exit :ghpull:`13668`, and a single typo fix in documentation: :ghpull:`13682`
1195 exit :ghpull:`13668`, and a single typo fix in documentation: :ghpull:`13682`
1196
1196
1197 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1197 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1198 work on IPython and related libraries.
1198 work on IPython and related libraries.
1199
1199
1200
1200
1201 .. _version 8.3.0:
1201 .. _version 8.3.0:
1202
1202
1203 IPython 8.3.0
1203 IPython 8.3.0
1204 -------------
1204 -------------
1205
1205
1206 - :ghpull:`13625`, using ``?``, ``??``, ``*?`` will not call
1206 - :ghpull:`13625`, using ``?``, ``??``, ``*?`` will not call
1207 ``set_next_input`` as most frontend allow proper multiline editing and it was
1207 ``set_next_input`` as most frontend allow proper multiline editing and it was
1208 causing issues for many users of multi-cell frontends. This has been backported to 7.33
1208 causing issues for many users of multi-cell frontends. This has been backported to 7.33
1209
1209
1210
1210
1211 - :ghpull:`13600`, ``pre_run_*``-hooks will now have a ``cell_id`` attribute on
1211 - :ghpull:`13600`, ``pre_run_*``-hooks will now have a ``cell_id`` attribute on
1212 the info object when frontend provides it. This has been backported to 7.33
1212 the info object when frontend provides it. This has been backported to 7.33
1213
1213
1214 - :ghpull:`13624`, fixed :kbd:`End` key being broken after accepting an
1214 - :ghpull:`13624`, fixed :kbd:`End` key being broken after accepting an
1215 auto-suggestion.
1215 auto-suggestion.
1216
1216
1217 - :ghpull:`13657` fixed an issue where history from different sessions would be mixed.
1217 - :ghpull:`13657` fixed an issue where history from different sessions would be mixed.
1218
1218
1219 .. _version 8.2.0:
1219 .. _version 8.2.0:
1220
1220
1221 IPython 8.2.0
1221 IPython 8.2.0
1222 -------------
1222 -------------
1223
1223
1224 IPython 8.2 mostly bring bugfixes to IPython.
1224 IPython 8.2 mostly bring bugfixes to IPython.
1225
1225
1226 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
1226 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
1227 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
1227 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
1228 - History is now pulled from the sqitel database and not from in-memory.
1228 - History is now pulled from the sqitel database and not from in-memory.
1229 In particular when using the ``%paste`` magic, the content of the pasted text will
1229 In particular when using the ``%paste`` magic, the content of the pasted text will
1230 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
1230 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
1231 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
1231 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
1232 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
1232 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
1233
1233
1234
1234
1235 I am still trying to fix and investigate :ghissue:`13598`, which seems to be
1235 I am still trying to fix and investigate :ghissue:`13598`, which seems to be
1236 random, and would appreciate help if you find a reproducible minimal case. I've
1236 random, and would appreciate help if you find a reproducible minimal case. I've
1237 tried to make various changes to the codebase to mitigate it, but a proper fix
1237 tried to make various changes to the codebase to mitigate it, but a proper fix
1238 will be difficult without understanding the cause.
1238 will be difficult without understanding the cause.
1239
1239
1240
1240
1241 All the issues on pull-requests for this release can be found in the `8.2
1241 All the issues on pull-requests for this release can be found in the `8.2
1242 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
1242 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
1243 documentation only PR can be found as part of the `7.33 milestone
1243 documentation only PR can be found as part of the `7.33 milestone
1244 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
1244 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
1245
1245
1246 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1246 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1247 work on IPython and related libraries.
1247 work on IPython and related libraries.
1248
1248
1249 .. _version 8.1.1:
1249 .. _version 8.1.1:
1250
1250
1251 IPython 8.1.1
1251 IPython 8.1.1
1252 -------------
1252 -------------
1253
1253
1254 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
1254 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
1255
1255
1256 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
1256 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
1257 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
1257 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
1258
1258
1259 .. _version 8.1:
1259 .. _version 8.1:
1260
1260
1261 IPython 8.1.0
1261 IPython 8.1.0
1262 -------------
1262 -------------
1263
1263
1264 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
1264 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
1265 updates a few behaviors that were problematic with the 8.0 as with many new major
1265 updates a few behaviors that were problematic with the 8.0 as with many new major
1266 release.
1266 release.
1267
1267
1268 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
1268 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
1269 features listed in :ref:`version 7.32`.
1269 features listed in :ref:`version 7.32`.
1270
1270
1271 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
1271 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
1272 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
1272 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
1273 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
1273 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
1274 is now explicit in ``setup.cfg``/``setup.py``
1274 is now explicit in ``setup.cfg``/``setup.py``
1275 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
1275 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
1276 - Multi-line edit executes too early with await. :ghpull:`13424`
1276 - Multi-line edit executes too early with await. :ghpull:`13424`
1277
1277
1278 - ``black`` is back as an optional dependency, and autoformatting disabled by
1278 - ``black`` is back as an optional dependency, and autoformatting disabled by
1279 default until some fixes are implemented (black improperly reformat magics).
1279 default until some fixes are implemented (black improperly reformat magics).
1280 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
1280 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
1281 reformatter has been added :ghpull:`13528` . You can use
1281 reformatter has been added :ghpull:`13528` . You can use
1282 ``TerminalInteractiveShell.autoformatter="black"``,
1282 ``TerminalInteractiveShell.autoformatter="black"``,
1283 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formatting
1283 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formatting
1284 with black, or switch to yapf.
1284 with black, or switch to yapf.
1285
1285
1286 - Fix and issue where ``display`` was not defined.
1286 - Fix and issue where ``display`` was not defined.
1287
1287
1288 - Auto suggestions are now configurable. Currently only
1288 - Auto suggestions are now configurable. Currently only
1289 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
1289 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
1290 welcomed. :ghpull:`13475`
1290 welcomed. :ghpull:`13475`
1291
1291
1292 - multiple packaging/testing improvement to simplify downstream packaging
1292 - multiple packaging/testing improvement to simplify downstream packaging
1293 (xfail with reasons, try to not access network...).
1293 (xfail with reasons, try to not access network...).
1294
1294
1295 - Update deprecation. ``InteractiveShell.magic`` internal method has been
1295 - Update deprecation. ``InteractiveShell.magic`` internal method has been
1296 deprecated for many years but did not emit a warning until now.
1296 deprecated for many years but did not emit a warning until now.
1297
1297
1298 - internal ``appended_to_syspath`` context manager has been deprecated.
1298 - internal ``appended_to_syspath`` context manager has been deprecated.
1299
1299
1300 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
1300 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
1301
1301
1302 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
1302 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
1303
1303
1304 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
1304 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
1305
1305
1306 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
1306 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
1307 removed.
1307 removed.
1308
1308
1309 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
1309 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
1310
1310
1311
1311
1312 We want to remind users that IPython is part of the Jupyter organisations, and
1312 We want to remind users that IPython is part of the Jupyter organisations, and
1313 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
1313 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
1314 Abuse and non-respectful comments on discussion will not be tolerated.
1314 Abuse and non-respectful comments on discussion will not be tolerated.
1315
1315
1316 Many thanks to all the contributors to this release, many of the above fixed issues and
1316 Many thanks to all the contributors to this release, many of the above fixed issues and
1317 new features were done by first time contributors, showing there is still
1317 new features were done by first time contributors, showing there is still
1318 plenty of easy contribution possible in IPython
1318 plenty of easy contribution possible in IPython
1319 . You can find all individual contributions
1319 . You can find all individual contributions
1320 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
1320 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
1321
1321
1322 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1322 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
1323 work on IPython and related libraries. In particular the Lazy autoloading of
1323 work on IPython and related libraries. In particular the Lazy autoloading of
1324 magics that you will find described in the 7.32 release notes.
1324 magics that you will find described in the 7.32 release notes.
1325
1325
1326
1326
1327 .. _version 8.0.1:
1327 .. _version 8.0.1:
1328
1328
1329 IPython 8.0.1 (CVE-2022-21699)
1329 IPython 8.0.1 (CVE-2022-21699)
1330 ------------------------------
1330 ------------------------------
1331
1331
1332 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
1332 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
1333 values in order to prevent potential Execution with Unnecessary Privileges.
1333 values in order to prevent potential Execution with Unnecessary Privileges.
1334
1334
1335 Almost all version of IPython looks for configuration and profiles in current
1335 Almost all version of IPython looks for configuration and profiles in current
1336 working directory. Since IPython was developed before pip and environments
1336 working directory. Since IPython was developed before pip and environments
1337 existed it was used a convenient way to load code/packages in a project
1337 existed it was used a convenient way to load code/packages in a project
1338 dependant way.
1338 dependant way.
1339
1339
1340 In 2022, it is not necessary anymore, and can lead to confusing behavior where
1340 In 2022, it is not necessary anymore, and can lead to confusing behavior where
1341 for example cloning a repository and starting IPython or loading a notebook from
1341 for example cloning a repository and starting IPython or loading a notebook from
1342 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
1342 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
1343 code execution.
1343 code execution.
1344
1344
1345
1345
1346 I did not find any standard way for packaged to advertise CVEs they fix, I'm
1346 I did not find any standard way for packaged to advertise CVEs they fix, I'm
1347 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
1347 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
1348 list the CVEs that should have been fixed. This attribute is informational only
1348 list the CVEs that should have been fixed. This attribute is informational only
1349 as if a executable has a flaw, this value can always be changed by an attacker.
1349 as if a executable has a flaw, this value can always be changed by an attacker.
1350
1350
1351 .. code::
1351 .. code::
1352
1352
1353 In [1]: import IPython
1353 In [1]: import IPython
1354
1354
1355 In [2]: IPython.__patched_cves__
1355 In [2]: IPython.__patched_cves__
1356 Out[2]: {'CVE-2022-21699'}
1356 Out[2]: {'CVE-2022-21699'}
1357
1357
1358 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
1358 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
1359 Out[3]: True
1359 Out[3]: True
1360
1360
1361 Thus starting with this version:
1361 Thus starting with this version:
1362
1362
1363 - The current working directory is not searched anymore for profiles or
1363 - The current working directory is not searched anymore for profiles or
1364 configurations files.
1364 configurations files.
1365 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
1365 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
1366 the list of fixed CVE. This is informational only.
1366 the list of fixed CVE. This is informational only.
1367
1367
1368 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
1368 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
1369
1369
1370
1370
1371 .. _version 8.0:
1371 .. _version 8.0:
1372
1372
1373 IPython 8.0
1373 IPython 8.0
1374 -----------
1374 -----------
1375
1375
1376 IPython 8.0 is bringing a large number of new features and improvements to both the
1376 IPython 8.0 is bringing a large number of new features and improvements to both the
1377 user of the terminal and of the kernel via Jupyter. The removal of compatibility
1377 user of the terminal and of the kernel via Jupyter. The removal of compatibility
1378 with an older version of Python is also the opportunity to do a couple of
1378 with an older version of Python is also the opportunity to do a couple of
1379 performance improvements in particular with respect to startup time.
1379 performance improvements in particular with respect to startup time.
1380 The 8.x branch started diverging from its predecessor around IPython 7.12
1380 The 8.x branch started diverging from its predecessor around IPython 7.12
1381 (January 2020).
1381 (January 2020).
1382
1382
1383 This release contains 250+ pull requests, in addition to many of the features
1383 This release contains 250+ pull requests, in addition to many of the features
1384 and backports that have made it to the 7.x branch. Please see the
1384 and backports that have made it to the 7.x branch. Please see the
1385 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
1385 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
1386
1386
1387 Please feel free to send pull requests to update those notes after release,
1387 Please feel free to send pull requests to update those notes after release,
1388 I have likely forgotten a few things reviewing 250+ PRs.
1388 I have likely forgotten a few things reviewing 250+ PRs.
1389
1389
1390 Dependencies changes/downstream packaging
1390 Dependencies changes/downstream packaging
1391 -----------------------------------------
1391 -----------------------------------------
1392
1392
1393 Most of our building steps have been changed to be (mostly) declarative
1393 Most of our building steps have been changed to be (mostly) declarative
1394 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
1394 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
1395 looking for help to do so.
1395 looking for help to do so.
1396
1396
1397 - minimum supported ``traitlets`` version is now 5+
1397 - minimum supported ``traitlets`` version is now 5+
1398 - we now require ``stack_data``
1398 - we now require ``stack_data``
1399 - minimal Python is now 3.8
1399 - minimal Python is now 3.8
1400 - ``nose`` is not a testing requirement anymore
1400 - ``nose`` is not a testing requirement anymore
1401 - ``pytest`` replaces nose.
1401 - ``pytest`` replaces nose.
1402 - ``iptest``/``iptest3`` cli entrypoints do not exist anymore.
1402 - ``iptest``/``iptest3`` cli entrypoints do not exist anymore.
1403 - the minimum officially ​supported ``numpy`` version has been bumped, but this should
1403 - the minimum officially ​supported ``numpy`` version has been bumped, but this should
1404 not have much effect on packaging.
1404 not have much effect on packaging.
1405
1405
1406
1406
1407 Deprecation and removal
1407 Deprecation and removal
1408 -----------------------
1408 -----------------------
1409
1409
1410 We removed almost all features, arguments, functions, and modules that were
1410 We removed almost all features, arguments, functions, and modules that were
1411 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
1411 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
1412 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
1412 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
1413 The few remaining deprecated features we left have better deprecation warnings
1413 The few remaining deprecated features we left have better deprecation warnings
1414 or have been turned into explicit errors for better error messages.
1414 or have been turned into explicit errors for better error messages.
1415
1415
1416 I will use this occasion to add the following requests to anyone emitting a
1416 I will use this occasion to add the following requests to anyone emitting a
1417 deprecation warning:
1417 deprecation warning:
1418
1418
1419 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
1419 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
1420 caller context, and not the callee one.
1420 caller context, and not the callee one.
1421 - Please add **since which version** something is deprecated.
1421 - Please add **since which version** something is deprecated.
1422
1422
1423 As a side note, it is much easier to conditionally compare version
1423 As a side note, it is much easier to conditionally compare version
1424 numbers rather than using ``try/except`` when functionality changes with a version.
1424 numbers rather than using ``try/except`` when functionality changes with a version.
1425
1425
1426 I won't list all the removed features here, but modules like ``IPython.kernel``,
1426 I won't list all the removed features here, but modules like ``IPython.kernel``,
1427 which was just a shim module around ``ipykernel`` for the past 8 years, have been
1427 which was just a shim module around ``ipykernel`` for the past 8 years, have been
1428 removed, and so many other similar things that pre-date the name **Jupyter**
1428 removed, and so many other similar things that pre-date the name **Jupyter**
1429 itself.
1429 itself.
1430
1430
1431 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
1431 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
1432 handled by ``load_extension``.
1432 handled by ``load_extension``.
1433
1433
1434 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
1434 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
1435 other packages and no longer need to be inside IPython.
1435 other packages and no longer need to be inside IPython.
1436
1436
1437
1437
1438 Documentation
1438 Documentation
1439 -------------
1439 -------------
1440
1440
1441 The majority of our docstrings have now been reformatted and automatically fixed by
1441 The majority of our docstrings have now been reformatted and automatically fixed by
1442 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
1442 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
1443 to numpydoc.
1443 to numpydoc.
1444
1444
1445 Type annotations
1445 Type annotations
1446 ----------------
1446 ----------------
1447
1447
1448 While IPython itself is highly dynamic and can't be completely typed, many of
1448 While IPython itself is highly dynamic and can't be completely typed, many of
1449 the functions now have type annotations, and part of the codebase is now checked
1449 the functions now have type annotations, and part of the codebase is now checked
1450 by mypy.
1450 by mypy.
1451
1451
1452
1452
1453 Featured changes
1453 Featured changes
1454 ----------------
1454 ----------------
1455
1455
1456 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
1456 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
1457 Please note as well that many features have been added in the 7.x branch as well
1457 Please note as well that many features have been added in the 7.x branch as well
1458 (and hence why you want to read the 7.x what's new notes), in particular
1458 (and hence why you want to read the 7.x what's new notes), in particular
1459 features contributed by QuantStack (with respect to debugger protocol and Xeus
1459 features contributed by QuantStack (with respect to debugger protocol and Xeus
1460 Python), as well as many debugger features that I was pleased to implement as
1460 Python), as well as many debugger features that I was pleased to implement as
1461 part of my work at QuanSight and sponsored by DE Shaw.
1461 part of my work at QuanSight and sponsored by DE Shaw.
1462
1462
1463 Traceback improvements
1463 Traceback improvements
1464 ~~~~~~~~~~~~~~~~~~~~~~
1464 ~~~~~~~~~~~~~~~~~~~~~~
1465
1465
1466 Previously, error tracebacks for errors happening in code cells were showing a
1466 Previously, error tracebacks for errors happening in code cells were showing a
1467 hash, the one used for compiling the Python AST::
1467 hash, the one used for compiling the Python AST::
1468
1468
1469 In [1]: def foo():
1469 In [1]: def foo():
1470 ...: return 3 / 0
1470 ...: return 3 / 0
1471 ...:
1471 ...:
1472
1472
1473 In [2]: foo()
1473 In [2]: foo()
1474 ---------------------------------------------------------------------------
1474 ---------------------------------------------------------------------------
1475 ZeroDivisionError Traceback (most recent call last)
1475 ZeroDivisionError Traceback (most recent call last)
1476 <ipython-input-2-c19b6d9633cf> in <module>
1476 <ipython-input-2-c19b6d9633cf> in <module>
1477 ----> 1 foo()
1477 ----> 1 foo()
1478
1478
1479 <ipython-input-1-1595a74c32d5> in foo()
1479 <ipython-input-1-1595a74c32d5> in foo()
1480 1 def foo():
1480 1 def foo():
1481 ----> 2 return 3 / 0
1481 ----> 2 return 3 / 0
1482 3
1482 3
1483
1483
1484 ZeroDivisionError: division by zero
1484 ZeroDivisionError: division by zero
1485
1485
1486 The error traceback is now correctly formatted, showing the cell number in which the error happened::
1486 The error traceback is now correctly formatted, showing the cell number in which the error happened::
1487
1487
1488 In [1]: def foo():
1488 In [1]: def foo():
1489 ...: return 3 / 0
1489 ...: return 3 / 0
1490 ...:
1490 ...:
1491
1491
1492 Input In [2]: foo()
1492 Input In [2]: foo()
1493 ---------------------------------------------------------------------------
1493 ---------------------------------------------------------------------------
1494 ZeroDivisionError Traceback (most recent call last)
1494 ZeroDivisionError Traceback (most recent call last)
1495 input In [2], in <module>
1495 input In [2], in <module>
1496 ----> 1 foo()
1496 ----> 1 foo()
1497
1497
1498 Input In [1], in foo()
1498 Input In [1], in foo()
1499 1 def foo():
1499 1 def foo():
1500 ----> 2 return 3 / 0
1500 ----> 2 return 3 / 0
1501
1501
1502 ZeroDivisionError: division by zero
1502 ZeroDivisionError: division by zero
1503
1503
1504 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
1504 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
1505 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
1505 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
1506
1506
1507 For example in the following snippet::
1507 For example in the following snippet::
1508
1508
1509 def foo(i):
1509 def foo(i):
1510 x = [[[0]]]
1510 x = [[[0]]]
1511 return x[0][i][0]
1511 return x[0][i][0]
1512
1512
1513
1513
1514 def bar():
1514 def bar():
1515 return foo(0) + foo(
1515 return foo(0) + foo(
1516 1
1516 1
1517 ) + foo(2)
1517 ) + foo(2)
1518
1518
1519
1519
1520 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
1520 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
1521 and IPython 8.0 is capable of telling you where the index error occurs::
1521 and IPython 8.0 is capable of telling you where the index error occurs::
1522
1522
1523
1523
1524 IndexError
1524 IndexError
1525 Input In [2], in <module>
1525 Input In [2], in <module>
1526 ----> 1 bar()
1526 ----> 1 bar()
1527 ^^^^^
1527 ^^^^^
1528
1528
1529 Input In [1], in bar()
1529 Input In [1], in bar()
1530 6 def bar():
1530 6 def bar():
1531 ----> 7 return foo(0) + foo(
1531 ----> 7 return foo(0) + foo(
1532 ^^^^
1532 ^^^^
1533 8 1
1533 8 1
1534 ^^^^^^^^
1534 ^^^^^^^^
1535 9 ) + foo(2)
1535 9 ) + foo(2)
1536 ^^^^
1536 ^^^^
1537
1537
1538 Input In [1], in foo(i)
1538 Input In [1], in foo(i)
1539 1 def foo(i):
1539 1 def foo(i):
1540 2 x = [[[0]]]
1540 2 x = [[[0]]]
1541 ----> 3 return x[0][i][0]
1541 ----> 3 return x[0][i][0]
1542 ^^^^^^^
1542 ^^^^^^^
1543
1543
1544 The corresponding locations marked here with ``^`` will show up highlighted in
1544 The corresponding locations marked here with ``^`` will show up highlighted in
1545 the terminal and notebooks.
1545 the terminal and notebooks.
1546
1546
1547 Finally, a colon ``::`` and line number is appended after a filename in
1547 Finally, a colon ``::`` and line number is appended after a filename in
1548 traceback::
1548 traceback::
1549
1549
1550
1550
1551 ZeroDivisionError Traceback (most recent call last)
1551 ZeroDivisionError Traceback (most recent call last)
1552 File ~/error.py:4, in <module>
1552 File ~/error.py:4, in <module>
1553 1 def f():
1553 1 def f():
1554 2 1/0
1554 2 1/0
1555 ----> 4 f()
1555 ----> 4 f()
1556
1556
1557 File ~/error.py:2, in f()
1557 File ~/error.py:2, in f()
1558 1 def f():
1558 1 def f():
1559 ----> 2 1/0
1559 ----> 2 1/0
1560
1560
1561 Many terminals and editors have integrations enabling you to directly jump to the
1561 Many terminals and editors have integrations enabling you to directly jump to the
1562 relevant file/line when this syntax is used, so this small addition may have a high
1562 relevant file/line when this syntax is used, so this small addition may have a high
1563 impact on productivity.
1563 impact on productivity.
1564
1564
1565
1565
1566 Autosuggestions
1566 Autosuggestions
1567 ~~~~~~~~~~~~~~~
1567 ~~~~~~~~~~~~~~~
1568
1568
1569 Autosuggestion is a very useful feature available in `fish <https://fishshell.com/>`__, `zsh <https://en.wikipedia.org/wiki/Z_shell>`__, and `prompt-toolkit <https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion>`__.
1569 Autosuggestion is a very useful feature available in `fish <https://fishshell.com/>`__, `zsh <https://en.wikipedia.org/wiki/Z_shell>`__, and `prompt-toolkit <https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion>`__.
1570
1570
1571 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
1571 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
1572 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
1572 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
1573
1573
1574 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
1574 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
1575 or right arrow as described below.
1575 or right arrow as described below.
1576
1576
1577 1. Start ipython
1577 1. Start ipython
1578
1578
1579 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
1579 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
1580
1580
1581 2. Run ``print("hello")``
1581 2. Run ``print("hello")``
1582
1582
1583 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
1583 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
1584
1584
1585 3. start typing ``print`` again to see the autosuggestion
1585 3. start typing ``print`` again to see the autosuggestion
1586
1586
1587 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
1587 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
1588
1588
1589 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
1589 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
1590
1590
1591 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
1591 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
1592
1592
1593 You can also complete word by word:
1593 You can also complete word by word:
1594
1594
1595 1. Run ``def say_hello(): print("hello")``
1595 1. Run ``def say_hello(): print("hello")``
1596
1596
1597 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
1597 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
1598
1598
1599 2. Start typing the first letter if ``def`` to see the autosuggestion
1599 2. Start typing the first letter if ``def`` to see the autosuggestion
1600
1600
1601 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
1601 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
1602
1602
1603 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
1603 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
1604
1604
1605 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
1605 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
1606
1606
1607 Importantly, this feature does not interfere with tab completion:
1607 Importantly, this feature does not interfere with tab completion:
1608
1608
1609 1. After running ``def say_hello(): print("hello")``, press d
1609 1. After running ``def say_hello(): print("hello")``, press d
1610
1610
1611 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
1611 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
1612
1612
1613 2. Press Tab to start tab completion
1613 2. Press Tab to start tab completion
1614
1614
1615 .. image:: ../_images/8.0/auto_suggest_d_completions.png
1615 .. image:: ../_images/8.0/auto_suggest_d_completions.png
1616
1616
1617 3A. Press Tab again to select the first option
1617 3A. Press Tab again to select the first option
1618
1618
1619 .. image:: ../_images/8.0/auto_suggest_def_completions.png
1619 .. image:: ../_images/8.0/auto_suggest_def_completions.png
1620
1620
1621 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
1621 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
1622
1622
1623 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
1623 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
1624
1624
1625 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
1625 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
1626
1626
1627 .. image:: ../_images/8.0/auto_suggest_match_parens.png
1627 .. image:: ../_images/8.0/auto_suggest_match_parens.png
1628
1628
1629
1629
1630 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
1630 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
1631
1631
1632 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
1632 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
1633 - To use these shortcuts in vi insert mode, you will have to create `custom keybindings in your config.py <https://github.com/mskar/setup/commit/2892fcee46f9f80ef7788f0749edc99daccc52f4/>`__.
1633 - To use these shortcuts in vi insert mode, you will have to create `custom keybindings in your config.py <https://github.com/mskar/setup/commit/2892fcee46f9f80ef7788f0749edc99daccc52f4/>`__.
1634
1634
1635
1635
1636 Show pinfo information in ipdb using "?" and "??"
1636 Show pinfo information in ipdb using "?" and "??"
1637 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1637 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1638
1638
1639 In IPDB, it is now possible to show the information about an object using "?"
1639 In IPDB, it is now possible to show the information about an object using "?"
1640 and "??", in much the same way that it can be done when using the IPython prompt::
1640 and "??", in much the same way that it can be done when using the IPython prompt::
1641
1641
1642 ipdb> partial?
1642 ipdb> partial?
1643 Init signature: partial(self, /, *args, **kwargs)
1643 Init signature: partial(self, /, *args, **kwargs)
1644 Docstring:
1644 Docstring:
1645 partial(func, *args, **keywords) - new function with partial application
1645 partial(func, *args, **keywords) - new function with partial application
1646 of the given arguments and keywords.
1646 of the given arguments and keywords.
1647 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
1647 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
1648 Type: type
1648 Type: type
1649 Subclasses:
1649 Subclasses:
1650
1650
1651 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
1651 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
1652
1652
1653
1653
1654 Autoreload 3 feature
1654 Autoreload 3 feature
1655 ~~~~~~~~~~~~~~~~~~~~
1655 ~~~~~~~~~~~~~~~~~~~~
1656
1656
1657 Example: When an IPython session is run with the 'autoreload' extension loaded,
1657 Example: When an IPython session is run with the 'autoreload' extension loaded,
1658 you will now have the option '3' to select, which means the following:
1658 you will now have the option '3' to select, which means the following:
1659
1659
1660 1. replicate all functionality from option 2
1660 1. replicate all functionality from option 2
1661 2. autoload all new funcs/classes/enums/globals from the module when they are added
1661 2. autoload all new funcs/classes/enums/globals from the module when they are added
1662 3. autoload all newly imported funcs/classes/enums/globals from external modules
1662 3. autoload all newly imported funcs/classes/enums/globals from external modules
1663
1663
1664 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
1664 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
1665
1665
1666 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
1666 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
1667
1667
1668 Auto formatting with black in the CLI
1668 Auto formatting with black in the CLI
1669 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1669 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1670
1670
1671 This feature was present in 7.x, but disabled by default.
1671 This feature was present in 7.x, but disabled by default.
1672
1672
1673 In 8.0, input was automatically reformatted with Black when black was installed.
1673 In 8.0, input was automatically reformatted with Black when black was installed.
1674 This feature has been reverted for the time being.
1674 This feature has been reverted for the time being.
1675 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
1675 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
1676
1676
1677 History Range Glob feature
1677 History Range Glob feature
1678 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1678 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1679
1679
1680 Previously, when using ``%history``, users could specify either
1680 Previously, when using ``%history``, users could specify either
1681 a range of sessions and lines, for example:
1681 a range of sessions and lines, for example:
1682
1682
1683 .. code-block:: python
1683 .. code-block:: python
1684
1684
1685 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
1685 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
1686 # to the fifth line of 6 sessions ago.``
1686 # to the fifth line of 6 sessions ago.``
1687
1687
1688 Or users could specify a glob pattern:
1688 Or users could specify a glob pattern:
1689
1689
1690 .. code-block:: python
1690 .. code-block:: python
1691
1691
1692 -g <pattern> # glob ALL history for the specified pattern.
1692 -g <pattern> # glob ALL history for the specified pattern.
1693
1693
1694 However users could *not* specify both.
1694 However users could *not* specify both.
1695
1695
1696 If a user *did* specify both a range and a glob pattern,
1696 If a user *did* specify both a range and a glob pattern,
1697 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
1697 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
1698
1698
1699 With this enhancement, if a user specifies both a range and a glob pattern, then the glob pattern will be applied to the specified range of history.
1699 With this enhancement, if a user specifies both a range and a glob pattern, then the glob pattern will be applied to the specified range of history.
1700
1700
1701 Don't start a multi-line cell with sunken parenthesis
1701 Don't start a multi-line cell with sunken parenthesis
1702 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1702 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1703
1703
1704 From now on, IPython will not ask for the next line of input when given a single
1704 From now on, IPython will not ask for the next line of input when given a single
1705 line with more closing than opening brackets. For example, this means that if
1705 line with more closing than opening brackets. For example, this means that if
1706 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
1706 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
1707 the ``...:`` prompt continuation.
1707 the ``...:`` prompt continuation.
1708
1708
1709 IPython shell for ipdb interact
1709 IPython shell for ipdb interact
1710 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1710 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1711
1711
1712 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
1712 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
1713
1713
1714 Automatic Vi prompt stripping
1714 Automatic Vi prompt stripping
1715 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1715 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1716
1716
1717 When pasting code into IPython, it will strip the leading prompt characters if
1717 When pasting code into IPython, it will strip the leading prompt characters if
1718 there are any. For example, you can paste the following code into the console -
1718 there are any. For example, you can paste the following code into the console -
1719 it will still work, even though each line is prefixed with prompts (``In``,
1719 it will still work, even though each line is prefixed with prompts (``In``,
1720 ``Out``)::
1720 ``Out``)::
1721
1721
1722 In [1]: 2 * 2 == 4
1722 In [1]: 2 * 2 == 4
1723 Out[1]: True
1723 Out[1]: True
1724
1724
1725 In [2]: print("This still works as pasted")
1725 In [2]: print("This still works as pasted")
1726
1726
1727
1727
1728 Previously, this was not the case for the Vi-mode prompts::
1728 Previously, this was not the case for the Vi-mode prompts::
1729
1729
1730 In [1]: [ins] In [13]: 2 * 2 == 4
1730 In [1]: [ins] In [13]: 2 * 2 == 4
1731 ...: Out[13]: True
1731 ...: Out[13]: True
1732 ...:
1732 ...:
1733 File "<ipython-input-1-727bb88eaf33>", line 1
1733 File "<ipython-input-1-727bb88eaf33>", line 1
1734 [ins] In [13]: 2 * 2 == 4
1734 [ins] In [13]: 2 * 2 == 4
1735 ^
1735 ^
1736 SyntaxError: invalid syntax
1736 SyntaxError: invalid syntax
1737
1737
1738 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
1738 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
1739 skipped just as the normal ``In`` would be.
1739 skipped just as the normal ``In`` would be.
1740
1740
1741 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
1741 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
1742 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
1742 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
1743
1743
1744 Empty History Ranges
1744 Empty History Ranges
1745 ~~~~~~~~~~~~~~~~~~~~
1745 ~~~~~~~~~~~~~~~~~~~~
1746
1746
1747 A number of magics that take history ranges can now be used with an empty
1747 A number of magics that take history ranges can now be used with an empty
1748 range. These magics are:
1748 range. These magics are:
1749
1749
1750 * ``%save``
1750 * ``%save``
1751 * ``%load``
1751 * ``%load``
1752 * ``%pastebin``
1752 * ``%pastebin``
1753 * ``%pycat``
1753 * ``%pycat``
1754
1754
1755 Using them this way will make them take the history of the current session up
1755 Using them this way will make them take the history of the current session up
1756 to the point of the magic call (such that the magic itself will not be
1756 to the point of the magic call (such that the magic itself will not be
1757 included).
1757 included).
1758
1758
1759 Therefore it is now possible to save the whole history to a file using
1759 Therefore it is now possible to save the whole history to a file using
1760 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
1760 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
1761 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
1761 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
1762 ``%pastebin``, or view the whole thing syntax-highlighted with a single
1762 ``%pastebin``, or view the whole thing syntax-highlighted with a single
1763 ``%pycat``.
1763 ``%pycat``.
1764
1764
1765
1765
1766 Windows timing implementation: Switch to process_time
1766 Windows timing implementation: Switch to process_time
1767 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1767 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1768 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
1768 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
1769 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
1769 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
1770 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
1770 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
1771
1771
1772 Miscellaneous
1772 Miscellaneous
1773 ~~~~~~~~~~~~~
1773 ~~~~~~~~~~~~~
1774 - Non-text formatters are not disabled in the terminal, which should simplify
1774 - Non-text formatters are not disabled in the terminal, which should simplify
1775 writing extensions displaying images or other mimetypes in supporting terminals.
1775 writing extensions displaying images or other mimetypes in supporting terminals.
1776 :ghpull:`12315`
1776 :ghpull:`12315`
1777 - It is now possible to automatically insert matching brackets in Terminal IPython using the
1777 - It is now possible to automatically insert matching brackets in Terminal IPython using the
1778 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
1778 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
1779 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
1779 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
1780 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
1780 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
1781 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
1781 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
1782 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
1782 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
1783 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
1783 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
1784 - The debugger now has a persistent history, which should make it less
1784 - The debugger now has a persistent history, which should make it less
1785 annoying to retype commands :ghpull:`13246`
1785 annoying to retype commands :ghpull:`13246`
1786 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
1786 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
1787 now warn users if they use one of those commands. :ghpull:`12954`
1787 now warn users if they use one of those commands. :ghpull:`12954`
1788 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
1788 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
1789
1789
1790 Re-added support for XDG config directories
1790 Re-added support for XDG config directories
1791 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1791 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1792
1792
1793 XDG support through the years comes and goes. There is a tension between having
1793 XDG support through the years comes and goes. There is a tension between having
1794 an identical location for configuration in all platforms versus having simple instructions.
1794 an identical location for configuration in all platforms versus having simple instructions.
1795 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
1795 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
1796 config files back into ``~/.ipython``. That migration code has now been removed.
1796 config files back into ``~/.ipython``. That migration code has now been removed.
1797 IPython now checks the XDG locations, so if you _manually_ move your config
1797 IPython now checks the XDG locations, so if you _manually_ move your config
1798 files to your preferred location, IPython will not move them back.
1798 files to your preferred location, IPython will not move them back.
1799
1799
1800
1800
1801 Preparing for Python 3.10
1801 Preparing for Python 3.10
1802 -------------------------
1802 -------------------------
1803
1803
1804 To prepare for Python 3.10, we have started working on removing reliance and
1804 To prepare for Python 3.10, we have started working on removing reliance and
1805 any dependency that is not compatible with Python 3.10. This includes migrating our
1805 any dependency that is not compatible with Python 3.10. This includes migrating our
1806 test suite to pytest and starting to remove nose. This also means that the
1806 test suite to pytest and starting to remove nose. This also means that the
1807 ``iptest`` command is now gone and all testing is via pytest.
1807 ``iptest`` command is now gone and all testing is via pytest.
1808
1808
1809 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
1809 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
1810 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
1810 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
1811 who did a fantastic job at updating our code base, migrating to pytest, pushing
1811 who did a fantastic job at updating our code base, migrating to pytest, pushing
1812 our coverage, and fixing a large number of bugs. I highly recommend contacting
1812 our coverage, and fixing a large number of bugs. I highly recommend contacting
1813 them if you need help with C++ and Python projects.
1813 them if you need help with C++ and Python projects.
1814
1814
1815 You can find all relevant issues and PRs with `the SDG 2021 tag <https://github.com/ipython/ipython/issues?q=label%3A%22Numfocus+SDG+2021%22+>`__
1815 You can find all relevant issues and PRs with `the SDG 2021 tag <https://github.com/ipython/ipython/issues?q=label%3A%22Numfocus+SDG+2021%22+>`__
1816
1816
1817 Removing support for older Python versions
1817 Removing support for older Python versions
1818 ------------------------------------------
1818 ------------------------------------------
1819
1819
1820
1820
1821 We are removing support for Python up through 3.7, allowing internal code to use the more
1821 We are removing support for Python up through 3.7, allowing internal code to use the more
1822 efficient ``pathlib`` and to make better use of type annotations.
1822 efficient ``pathlib`` and to make better use of type annotations.
1823
1823
1824 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
1824 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
1825 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
1825 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
1826
1826
1827
1827
1828 We had about 34 PRs only to update some logic to update some functions from managing strings to
1828 We had about 34 PRs only to update some logic to update some functions from managing strings to
1829 using Pathlib.
1829 using Pathlib.
1830
1830
1831 The completer has also seen significant updates and now makes use of newer Jedi APIs,
1831 The completer has also seen significant updates and now makes use of newer Jedi APIs,
1832 offering faster and more reliable tab completion.
1832 offering faster and more reliable tab completion.
1833
1833
1834 Misc Statistics
1834 Misc Statistics
1835 ---------------
1835 ---------------
1836
1836
1837 Here are some numbers::
1837 Here are some numbers::
1838
1838
1839 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
1839 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
1840 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
1840 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
1841
1841
1842 $ git diff --stat 7.x...master | tail -1
1842 $ git diff --stat 7.x...master | tail -1
1843 340 files changed, 13399 insertions(+), 12421 deletions(-)
1843 340 files changed, 13399 insertions(+), 12421 deletions(-)
1844
1844
1845 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
1845 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
1846 maintainers pushing buttons).::
1846 maintainers pushing buttons).::
1847
1847
1848 $ git shortlog -s --no-merges 7.x...master | sort -nr
1848 $ git shortlog -s --no-merges 7.x...master | sort -nr
1849 535 Matthias Bussonnier
1849 535 Matthias Bussonnier
1850 86 Nikita Kniazev
1850 86 Nikita Kniazev
1851 69 Blazej Michalik
1851 69 Blazej Michalik
1852 49 Samuel Gaist
1852 49 Samuel Gaist
1853 27 Itamar Turner-Trauring
1853 27 Itamar Turner-Trauring
1854 18 Spas Kalaydzhisyki
1854 18 Spas Kalaydzhisyki
1855 17 Thomas Kluyver
1855 17 Thomas Kluyver
1856 17 Quentin Peter
1856 17 Quentin Peter
1857 17 James Morris
1857 17 James Morris
1858 17 Artur Svistunov
1858 17 Artur Svistunov
1859 15 Bart Skowron
1859 15 Bart Skowron
1860 14 Alex Hall
1860 14 Alex Hall
1861 13 rushabh-v
1861 13 rushabh-v
1862 13 Terry Davis
1862 13 Terry Davis
1863 13 Benjamin Ragan-Kelley
1863 13 Benjamin Ragan-Kelley
1864 8 martinRenou
1864 8 martinRenou
1865 8 farisachugthai
1865 8 farisachugthai
1866 7 dswij
1866 7 dswij
1867 7 Gal B
1867 7 Gal B
1868 7 Corentin Cadiou
1868 7 Corentin Cadiou
1869 6 yuji96
1869 6 yuji96
1870 6 Martin Skarzynski
1870 6 Martin Skarzynski
1871 6 Justin Palmer
1871 6 Justin Palmer
1872 6 Daniel Goldfarb
1872 6 Daniel Goldfarb
1873 6 Ben Greiner
1873 6 Ben Greiner
1874 5 Sammy Al Hashemi
1874 5 Sammy Al Hashemi
1875 5 Paul Ivanov
1875 5 Paul Ivanov
1876 5 Inception95
1876 5 Inception95
1877 5 Eyenpi
1877 5 Eyenpi
1878 5 Douglas Blank
1878 5 Douglas Blank
1879 5 Coco Mishra
1879 5 Coco Mishra
1880 5 Bibo Hao
1880 5 Bibo Hao
1881 5 AndrΓ© A. Gomes
1881 5 AndrΓ© A. Gomes
1882 5 Ahmed Fasih
1882 5 Ahmed Fasih
1883 4 takuya fujiwara
1883 4 takuya fujiwara
1884 4 palewire
1884 4 palewire
1885 4 Thomas A Caswell
1885 4 Thomas A Caswell
1886 4 Talley Lambert
1886 4 Talley Lambert
1887 4 Scott Sanderson
1887 4 Scott Sanderson
1888 4 Ram Rachum
1888 4 Ram Rachum
1889 4 Nick Muoh
1889 4 Nick Muoh
1890 4 Nathan Goldbaum
1890 4 Nathan Goldbaum
1891 4 Mithil Poojary
1891 4 Mithil Poojary
1892 4 Michael T
1892 4 Michael T
1893 4 Jakub Klus
1893 4 Jakub Klus
1894 4 Ian Castleden
1894 4 Ian Castleden
1895 4 Eli Rykoff
1895 4 Eli Rykoff
1896 4 Ashwin Vishnu
1896 4 Ashwin Vishnu
1897 3 谭九鼎
1897 3 谭九鼎
1898 3 sleeping
1898 3 sleeping
1899 3 Sylvain Corlay
1899 3 Sylvain Corlay
1900 3 Peter Corke
1900 3 Peter Corke
1901 3 Paul Bissex
1901 3 Paul Bissex
1902 3 Matthew Feickert
1902 3 Matthew Feickert
1903 3 Fernando Perez
1903 3 Fernando Perez
1904 3 Eric Wieser
1904 3 Eric Wieser
1905 3 Daniel Mietchen
1905 3 Daniel Mietchen
1906 3 Aditya Sathe
1906 3 Aditya Sathe
1907 3 007vedant
1907 3 007vedant
1908 2 rchiodo
1908 2 rchiodo
1909 2 nicolaslazo
1909 2 nicolaslazo
1910 2 luttik
1910 2 luttik
1911 2 gorogoroumaru
1911 2 gorogoroumaru
1912 2 foobarbyte
1912 2 foobarbyte
1913 2 bar-hen
1913 2 bar-hen
1914 2 Theo Ouzhinski
1914 2 Theo Ouzhinski
1915 2 Strawkage
1915 2 Strawkage
1916 2 Samreen Zarroug
1916 2 Samreen Zarroug
1917 2 Pete Blois
1917 2 Pete Blois
1918 2 Meysam Azad
1918 2 Meysam Azad
1919 2 Matthieu Ancellin
1919 2 Matthieu Ancellin
1920 2 Mark Schmitz
1920 2 Mark Schmitz
1921 2 Maor Kleinberger
1921 2 Maor Kleinberger
1922 2 MRCWirtz
1922 2 MRCWirtz
1923 2 Lumir Balhar
1923 2 Lumir Balhar
1924 2 Julien Rabinow
1924 2 Julien Rabinow
1925 2 Juan Luis Cano RodrΓ­guez
1925 2 Juan Luis Cano RodrΓ­guez
1926 2 Joyce Er
1926 2 Joyce Er
1927 2 Jakub
1927 2 Jakub
1928 2 Faris A Chugthai
1928 2 Faris A Chugthai
1929 2 Ethan Madden
1929 2 Ethan Madden
1930 2 Dimitri Papadopoulos
1930 2 Dimitri Papadopoulos
1931 2 Diego Fernandez
1931 2 Diego Fernandez
1932 2 Daniel Shimon
1932 2 Daniel Shimon
1933 2 Coco Bennett
1933 2 Coco Bennett
1934 2 Carlos Cordoba
1934 2 Carlos Cordoba
1935 2 Boyuan Liu
1935 2 Boyuan Liu
1936 2 BaoGiang HoangVu
1936 2 BaoGiang HoangVu
1937 2 Augusto
1937 2 Augusto
1938 2 Arthur Svistunov
1938 2 Arthur Svistunov
1939 2 Arthur Moreira
1939 2 Arthur Moreira
1940 2 Ali Nabipour
1940 2 Ali Nabipour
1941 2 Adam Hackbarth
1941 2 Adam Hackbarth
1942 1 richard
1942 1 richard
1943 1 linar-jether
1943 1 linar-jether
1944 1 lbennett
1944 1 lbennett
1945 1 juacrumar
1945 1 juacrumar
1946 1 gpotter2
1946 1 gpotter2
1947 1 digitalvirtuoso
1947 1 digitalvirtuoso
1948 1 dalthviz
1948 1 dalthviz
1949 1 Yonatan Goldschmidt
1949 1 Yonatan Goldschmidt
1950 1 Tomasz KΕ‚oczko
1950 1 Tomasz KΕ‚oczko
1951 1 Tobias Bengfort
1951 1 Tobias Bengfort
1952 1 Timur Kushukov
1952 1 Timur Kushukov
1953 1 Thomas
1953 1 Thomas
1954 1 Snir Broshi
1954 1 Snir Broshi
1955 1 Shao Yang Hong
1955 1 Shao Yang Hong
1956 1 Sanjana-03
1956 1 Sanjana-03
1957 1 Romulo Filho
1957 1 Romulo Filho
1958 1 Rodolfo Carvalho
1958 1 Rodolfo Carvalho
1959 1 Richard Shadrach
1959 1 Richard Shadrach
1960 1 Reilly Tucker Siemens
1960 1 Reilly Tucker Siemens
1961 1 Rakessh Roshan
1961 1 Rakessh Roshan
1962 1 Piers Titus van der Torren
1962 1 Piers Titus van der Torren
1963 1 PhanatosZou
1963 1 PhanatosZou
1964 1 Pavel Safronov
1964 1 Pavel Safronov
1965 1 Paulo S. Costa
1965 1 Paulo S. Costa
1966 1 Paul McCarthy
1966 1 Paul McCarthy
1967 1 NotWearingPants
1967 1 NotWearingPants
1968 1 Naelson Douglas
1968 1 Naelson Douglas
1969 1 Michael Tiemann
1969 1 Michael Tiemann
1970 1 Matt Wozniski
1970 1 Matt Wozniski
1971 1 Markus Wageringel
1971 1 Markus Wageringel
1972 1 Marcus Wirtz
1972 1 Marcus Wirtz
1973 1 Marcio Mazza
1973 1 Marcio Mazza
1974 1 LumΓ­r 'Frenzy' Balhar
1974 1 LumΓ­r 'Frenzy' Balhar
1975 1 Lightyagami1
1975 1 Lightyagami1
1976 1 Leon Anavi
1976 1 Leon Anavi
1977 1 LeafyLi
1977 1 LeafyLi
1978 1 L0uisJ0shua
1978 1 L0uisJ0shua
1979 1 Kyle Cutler
1979 1 Kyle Cutler
1980 1 Krzysztof Cybulski
1980 1 Krzysztof Cybulski
1981 1 Kevin Kirsche
1981 1 Kevin Kirsche
1982 1 KIU Shueng Chuan
1982 1 KIU Shueng Chuan
1983 1 Jonathan Slenders
1983 1 Jonathan Slenders
1984 1 Jay Qi
1984 1 Jay Qi
1985 1 Jake VanderPlas
1985 1 Jake VanderPlas
1986 1 Iwan Briquemont
1986 1 Iwan Briquemont
1987 1 Hussaina Begum Nandyala
1987 1 Hussaina Begum Nandyala
1988 1 Gordon Ball
1988 1 Gordon Ball
1989 1 Gabriel Simonetto
1989 1 Gabriel Simonetto
1990 1 Frank Tobia
1990 1 Frank Tobia
1991 1 Erik
1991 1 Erik
1992 1 Elliott Sales de Andrade
1992 1 Elliott Sales de Andrade
1993 1 Daniel Hahler
1993 1 Daniel Hahler
1994 1 Dan Green-Leipciger
1994 1 Dan Green-Leipciger
1995 1 Dan Green
1995 1 Dan Green
1996 1 Damian Yurzola
1996 1 Damian Yurzola
1997 1 Coon, Ethan T
1997 1 Coon, Ethan T
1998 1 Carol Willing
1998 1 Carol Willing
1999 1 Brian Lee
1999 1 Brian Lee
2000 1 Brendan Gerrity
2000 1 Brendan Gerrity
2001 1 Blake Griffin
2001 1 Blake Griffin
2002 1 Bastian Ebeling
2002 1 Bastian Ebeling
2003 1 Bartosz Telenczuk
2003 1 Bartosz Telenczuk
2004 1 Ankitsingh6299
2004 1 Ankitsingh6299
2005 1 Andrew Port
2005 1 Andrew Port
2006 1 Andrew J. Hesford
2006 1 Andrew J. Hesford
2007 1 Albert Zhang
2007 1 Albert Zhang
2008 1 Adam Johnson
2008 1 Adam Johnson
2009
2009
2010 This does not, of course, represent non-code contributions, for which we are also grateful.
2010 This does not, of course, represent non-code contributions, for which we are also grateful.
2011
2011
2012
2012
2013 API Changes using Frappuccino
2013 API Changes using Frappuccino
2014 -----------------------------
2014 -----------------------------
2015
2015
2016 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
2016 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
2017
2017
2018
2018
2019 The following items are new in IPython 8.0 ::
2019 The following items are new in IPython 8.0 ::
2020
2020
2021 + IPython.core.async_helpers.get_asyncio_loop()
2021 + IPython.core.async_helpers.get_asyncio_loop()
2022 + IPython.core.completer.Dict
2022 + IPython.core.completer.Dict
2023 + IPython.core.completer.Pattern
2023 + IPython.core.completer.Pattern
2024 + IPython.core.completer.Sequence
2024 + IPython.core.completer.Sequence
2025 + IPython.core.completer.__skip_doctest__
2025 + IPython.core.completer.__skip_doctest__
2026 + IPython.core.debugger.Pdb.precmd(self, line)
2026 + IPython.core.debugger.Pdb.precmd(self, line)
2027 + IPython.core.debugger.__skip_doctest__
2027 + IPython.core.debugger.__skip_doctest__
2028 + IPython.core.display.__getattr__(name)
2028 + IPython.core.display.__getattr__(name)
2029 + IPython.core.display.warn
2029 + IPython.core.display.warn
2030 + IPython.core.display_functions
2030 + IPython.core.display_functions
2031 + IPython.core.display_functions.DisplayHandle
2031 + IPython.core.display_functions.DisplayHandle
2032 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
2032 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
2033 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
2033 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
2034 + IPython.core.display_functions.__all__
2034 + IPython.core.display_functions.__all__
2035 + IPython.core.display_functions.__builtins__
2035 + IPython.core.display_functions.__builtins__
2036 + IPython.core.display_functions.__cached__
2036 + IPython.core.display_functions.__cached__
2037 + IPython.core.display_functions.__doc__
2037 + IPython.core.display_functions.__doc__
2038 + IPython.core.display_functions.__file__
2038 + IPython.core.display_functions.__file__
2039 + IPython.core.display_functions.__loader__
2039 + IPython.core.display_functions.__loader__
2040 + IPython.core.display_functions.__name__
2040 + IPython.core.display_functions.__name__
2041 + IPython.core.display_functions.__package__
2041 + IPython.core.display_functions.__package__
2042 + IPython.core.display_functions.__spec__
2042 + IPython.core.display_functions.__spec__
2043 + IPython.core.display_functions.b2a_hex
2043 + IPython.core.display_functions.b2a_hex
2044 + IPython.core.display_functions.clear_output(wait=False)
2044 + IPython.core.display_functions.clear_output(wait=False)
2045 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
2045 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
2046 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
2046 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
2047 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
2047 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
2048 + IPython.core.extensions.BUILTINS_EXTS
2048 + IPython.core.extensions.BUILTINS_EXTS
2049 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
2049 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
2050 + IPython.core.interactiveshell.Callable
2050 + IPython.core.interactiveshell.Callable
2051 + IPython.core.interactiveshell.__annotations__
2051 + IPython.core.interactiveshell.__annotations__
2052 + IPython.core.ultratb.List
2052 + IPython.core.ultratb.List
2053 + IPython.core.ultratb.Tuple
2053 + IPython.core.ultratb.Tuple
2054 + IPython.lib.pretty.CallExpression
2054 + IPython.lib.pretty.CallExpression
2055 + IPython.lib.pretty.CallExpression.factory(name)
2055 + IPython.lib.pretty.CallExpression.factory(name)
2056 + IPython.lib.pretty.RawStringLiteral
2056 + IPython.lib.pretty.RawStringLiteral
2057 + IPython.lib.pretty.RawText
2057 + IPython.lib.pretty.RawText
2058 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
2058 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
2059 + IPython.terminal.embed.Set
2059 + IPython.terminal.embed.Set
2060
2060
2061 The following items have been removed (or moved to superclass)::
2061 The following items have been removed (or moved to superclass)::
2062
2062
2063 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
2063 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
2064 - IPython.core.completer.Sentinel
2064 - IPython.core.completer.Sentinel
2065 - IPython.core.completer.skip_doctest
2065 - IPython.core.completer.skip_doctest
2066 - IPython.core.debugger.Tracer
2066 - IPython.core.debugger.Tracer
2067 - IPython.core.display.DisplayHandle
2067 - IPython.core.display.DisplayHandle
2068 - IPython.core.display.DisplayHandle.display
2068 - IPython.core.display.DisplayHandle.display
2069 - IPython.core.display.DisplayHandle.update
2069 - IPython.core.display.DisplayHandle.update
2070 - IPython.core.display.b2a_hex
2070 - IPython.core.display.b2a_hex
2071 - IPython.core.display.clear_output
2071 - IPython.core.display.clear_output
2072 - IPython.core.display.display
2072 - IPython.core.display.display
2073 - IPython.core.display.publish_display_data
2073 - IPython.core.display.publish_display_data
2074 - IPython.core.display.update_display
2074 - IPython.core.display.update_display
2075 - IPython.core.excolors.Deprec
2075 - IPython.core.excolors.Deprec
2076 - IPython.core.excolors.ExceptionColors
2076 - IPython.core.excolors.ExceptionColors
2077 - IPython.core.history.warn
2077 - IPython.core.history.warn
2078 - IPython.core.hooks.late_startup_hook
2078 - IPython.core.hooks.late_startup_hook
2079 - IPython.core.hooks.pre_run_code_hook
2079 - IPython.core.hooks.pre_run_code_hook
2080 - IPython.core.hooks.shutdown_hook
2080 - IPython.core.hooks.shutdown_hook
2081 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
2081 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
2082 - IPython.core.interactiveshell.InteractiveShell.init_readline
2082 - IPython.core.interactiveshell.InteractiveShell.init_readline
2083 - IPython.core.interactiveshell.InteractiveShell.write
2083 - IPython.core.interactiveshell.InteractiveShell.write
2084 - IPython.core.interactiveshell.InteractiveShell.write_err
2084 - IPython.core.interactiveshell.InteractiveShell.write_err
2085 - IPython.core.interactiveshell.get_default_colors
2085 - IPython.core.interactiveshell.get_default_colors
2086 - IPython.core.interactiveshell.removed_co_newlocals
2086 - IPython.core.interactiveshell.removed_co_newlocals
2087 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
2087 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
2088 - IPython.core.magics.script.PIPE
2088 - IPython.core.magics.script.PIPE
2089 - IPython.core.prefilter.PrefilterManager.init_transformers
2089 - IPython.core.prefilter.PrefilterManager.init_transformers
2090 - IPython.core.release.classifiers
2090 - IPython.core.release.classifiers
2091 - IPython.core.release.description
2091 - IPython.core.release.description
2092 - IPython.core.release.keywords
2092 - IPython.core.release.keywords
2093 - IPython.core.release.long_description
2093 - IPython.core.release.long_description
2094 - IPython.core.release.name
2094 - IPython.core.release.name
2095 - IPython.core.release.platforms
2095 - IPython.core.release.platforms
2096 - IPython.core.release.url
2096 - IPython.core.release.url
2097 - IPython.core.ultratb.VerboseTB.format_records
2097 - IPython.core.ultratb.VerboseTB.format_records
2098 - IPython.core.ultratb.find_recursion
2098 - IPython.core.ultratb.find_recursion
2099 - IPython.core.ultratb.findsource
2099 - IPython.core.ultratb.findsource
2100 - IPython.core.ultratb.fix_frame_records_filenames
2100 - IPython.core.ultratb.fix_frame_records_filenames
2101 - IPython.core.ultratb.inspect_error
2101 - IPython.core.ultratb.inspect_error
2102 - IPython.core.ultratb.is_recursion_error
2102 - IPython.core.ultratb.is_recursion_error
2103 - IPython.core.ultratb.with_patch_inspect
2103 - IPython.core.ultratb.with_patch_inspect
2104 - IPython.external.__all__
2104 - IPython.external.__all__
2105 - IPython.external.__builtins__
2105 - IPython.external.__builtins__
2106 - IPython.external.__cached__
2106 - IPython.external.__cached__
2107 - IPython.external.__doc__
2107 - IPython.external.__doc__
2108 - IPython.external.__file__
2108 - IPython.external.__file__
2109 - IPython.external.__loader__
2109 - IPython.external.__loader__
2110 - IPython.external.__name__
2110 - IPython.external.__name__
2111 - IPython.external.__package__
2111 - IPython.external.__package__
2112 - IPython.external.__path__
2112 - IPython.external.__path__
2113 - IPython.external.__spec__
2113 - IPython.external.__spec__
2114 - IPython.kernel.KernelConnectionInfo
2114 - IPython.kernel.KernelConnectionInfo
2115 - IPython.kernel.__builtins__
2115 - IPython.kernel.__builtins__
2116 - IPython.kernel.__cached__
2116 - IPython.kernel.__cached__
2117 - IPython.kernel.__warningregistry__
2117 - IPython.kernel.__warningregistry__
2118 - IPython.kernel.pkg
2118 - IPython.kernel.pkg
2119 - IPython.kernel.protocol_version
2119 - IPython.kernel.protocol_version
2120 - IPython.kernel.protocol_version_info
2120 - IPython.kernel.protocol_version_info
2121 - IPython.kernel.src
2121 - IPython.kernel.src
2122 - IPython.kernel.version_info
2122 - IPython.kernel.version_info
2123 - IPython.kernel.warn
2123 - IPython.kernel.warn
2124 - IPython.lib.backgroundjobs
2124 - IPython.lib.backgroundjobs
2125 - IPython.lib.backgroundjobs.BackgroundJobBase
2125 - IPython.lib.backgroundjobs.BackgroundJobBase
2126 - IPython.lib.backgroundjobs.BackgroundJobBase.run
2126 - IPython.lib.backgroundjobs.BackgroundJobBase.run
2127 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
2127 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
2128 - IPython.lib.backgroundjobs.BackgroundJobExpr
2128 - IPython.lib.backgroundjobs.BackgroundJobExpr
2129 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
2129 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
2130 - IPython.lib.backgroundjobs.BackgroundJobFunc
2130 - IPython.lib.backgroundjobs.BackgroundJobFunc
2131 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
2131 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
2132 - IPython.lib.backgroundjobs.BackgroundJobManager
2132 - IPython.lib.backgroundjobs.BackgroundJobManager
2133 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
2133 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
2134 - IPython.lib.backgroundjobs.BackgroundJobManager.new
2134 - IPython.lib.backgroundjobs.BackgroundJobManager.new
2135 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
2135 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
2136 - IPython.lib.backgroundjobs.BackgroundJobManager.result
2136 - IPython.lib.backgroundjobs.BackgroundJobManager.result
2137 - IPython.lib.backgroundjobs.BackgroundJobManager.status
2137 - IPython.lib.backgroundjobs.BackgroundJobManager.status
2138 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
2138 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
2139 - IPython.lib.backgroundjobs.__builtins__
2139 - IPython.lib.backgroundjobs.__builtins__
2140 - IPython.lib.backgroundjobs.__cached__
2140 - IPython.lib.backgroundjobs.__cached__
2141 - IPython.lib.backgroundjobs.__doc__
2141 - IPython.lib.backgroundjobs.__doc__
2142 - IPython.lib.backgroundjobs.__file__
2142 - IPython.lib.backgroundjobs.__file__
2143 - IPython.lib.backgroundjobs.__loader__
2143 - IPython.lib.backgroundjobs.__loader__
2144 - IPython.lib.backgroundjobs.__name__
2144 - IPython.lib.backgroundjobs.__name__
2145 - IPython.lib.backgroundjobs.__package__
2145 - IPython.lib.backgroundjobs.__package__
2146 - IPython.lib.backgroundjobs.__spec__
2146 - IPython.lib.backgroundjobs.__spec__
2147 - IPython.lib.kernel.__builtins__
2147 - IPython.lib.kernel.__builtins__
2148 - IPython.lib.kernel.__cached__
2148 - IPython.lib.kernel.__cached__
2149 - IPython.lib.kernel.__doc__
2149 - IPython.lib.kernel.__doc__
2150 - IPython.lib.kernel.__file__
2150 - IPython.lib.kernel.__file__
2151 - IPython.lib.kernel.__loader__
2151 - IPython.lib.kernel.__loader__
2152 - IPython.lib.kernel.__name__
2152 - IPython.lib.kernel.__name__
2153 - IPython.lib.kernel.__package__
2153 - IPython.lib.kernel.__package__
2154 - IPython.lib.kernel.__spec__
2154 - IPython.lib.kernel.__spec__
2155 - IPython.lib.kernel.__warningregistry__
2155 - IPython.lib.kernel.__warningregistry__
2156 - IPython.paths.fs_encoding
2156 - IPython.paths.fs_encoding
2157 - IPython.terminal.debugger.DEFAULT_BUFFER
2157 - IPython.terminal.debugger.DEFAULT_BUFFER
2158 - IPython.terminal.debugger.cursor_in_leading_ws
2158 - IPython.terminal.debugger.cursor_in_leading_ws
2159 - IPython.terminal.debugger.emacs_insert_mode
2159 - IPython.terminal.debugger.emacs_insert_mode
2160 - IPython.terminal.debugger.has_selection
2160 - IPython.terminal.debugger.has_selection
2161 - IPython.terminal.debugger.vi_insert_mode
2161 - IPython.terminal.debugger.vi_insert_mode
2162 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
2162 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
2163 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
2163 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
2164 - IPython.testing.test
2164 - IPython.testing.test
2165 - IPython.utils.contexts.NoOpContext
2165 - IPython.utils.contexts.NoOpContext
2166 - IPython.utils.io.IOStream
2166 - IPython.utils.io.IOStream
2167 - IPython.utils.io.IOStream.close
2167 - IPython.utils.io.IOStream.close
2168 - IPython.utils.io.IOStream.write
2168 - IPython.utils.io.IOStream.write
2169 - IPython.utils.io.IOStream.writelines
2169 - IPython.utils.io.IOStream.writelines
2170 - IPython.utils.io.__warningregistry__
2170 - IPython.utils.io.__warningregistry__
2171 - IPython.utils.io.atomic_writing
2171 - IPython.utils.io.atomic_writing
2172 - IPython.utils.io.stderr
2172 - IPython.utils.io.stderr
2173 - IPython.utils.io.stdin
2173 - IPython.utils.io.stdin
2174 - IPython.utils.io.stdout
2174 - IPython.utils.io.stdout
2175 - IPython.utils.io.unicode_std_stream
2175 - IPython.utils.io.unicode_std_stream
2176 - IPython.utils.path.get_ipython_cache_dir
2176 - IPython.utils.path.get_ipython_cache_dir
2177 - IPython.utils.path.get_ipython_dir
2177 - IPython.utils.path.get_ipython_dir
2178 - IPython.utils.path.get_ipython_module_path
2178 - IPython.utils.path.get_ipython_module_path
2179 - IPython.utils.path.get_ipython_package_dir
2179 - IPython.utils.path.get_ipython_package_dir
2180 - IPython.utils.path.locate_profile
2180 - IPython.utils.path.locate_profile
2181 - IPython.utils.path.unquote_filename
2181 - IPython.utils.path.unquote_filename
2182 - IPython.utils.py3compat.PY2
2182 - IPython.utils.py3compat.PY2
2183 - IPython.utils.py3compat.PY3
2183 - IPython.utils.py3compat.PY3
2184 - IPython.utils.py3compat.buffer_to_bytes
2184 - IPython.utils.py3compat.buffer_to_bytes
2185 - IPython.utils.py3compat.builtin_mod_name
2185 - IPython.utils.py3compat.builtin_mod_name
2186 - IPython.utils.py3compat.cast_bytes
2186 - IPython.utils.py3compat.cast_bytes
2187 - IPython.utils.py3compat.getcwd
2187 - IPython.utils.py3compat.getcwd
2188 - IPython.utils.py3compat.isidentifier
2188 - IPython.utils.py3compat.isidentifier
2189 - IPython.utils.py3compat.u_format
2189 - IPython.utils.py3compat.u_format
2190
2190
2191 The following signatures differ between 7.x and 8.0::
2191 The following signatures differ between 7.x and 8.0::
2192
2192
2193 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
2193 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
2194 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
2194 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
2195
2195
2196 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
2196 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
2197 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
2197 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
2198
2198
2199 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
2199 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
2200 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
2200 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
2201
2201
2202 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
2202 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
2203 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
2203 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
2204
2204
2205 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
2205 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
2206 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
2206 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
2207
2207
2208 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
2208 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
2209 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
2209 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
2210
2210
2211 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
2211 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
2212 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
2212 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
2213
2213
2214 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
2214 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
2215 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
2215 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
2216
2216
2217 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
2217 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
2218 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
2218 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
2219
2219
2220 - IPython.terminal.embed.embed(**kwargs)
2220 - IPython.terminal.embed.embed(**kwargs)
2221 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
2221 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
2222
2222
2223 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
2223 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
2224 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
2224 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
2225
2225
2226 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
2226 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
2227 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
2227 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
2228
2228
2229 - IPython.utils.path.get_py_filename(name, force_win32='None')
2229 - IPython.utils.path.get_py_filename(name, force_win32='None')
2230 + IPython.utils.path.get_py_filename(name)
2230 + IPython.utils.path.get_py_filename(name)
2231
2231
2232 The following are new attributes (that might be inherited)::
2232 The following are new attributes (that might be inherited)::
2233
2233
2234 + IPython.core.completer.IPCompleter.unicode_names
2234 + IPython.core.completer.IPCompleter.unicode_names
2235 + IPython.core.debugger.InterruptiblePdb.precmd
2235 + IPython.core.debugger.InterruptiblePdb.precmd
2236 + IPython.core.debugger.Pdb.precmd
2236 + IPython.core.debugger.Pdb.precmd
2237 + IPython.core.ultratb.AutoFormattedTB.has_colors
2237 + IPython.core.ultratb.AutoFormattedTB.has_colors
2238 + IPython.core.ultratb.ColorTB.has_colors
2238 + IPython.core.ultratb.ColorTB.has_colors
2239 + IPython.core.ultratb.FormattedTB.has_colors
2239 + IPython.core.ultratb.FormattedTB.has_colors
2240 + IPython.core.ultratb.ListTB.has_colors
2240 + IPython.core.ultratb.ListTB.has_colors
2241 + IPython.core.ultratb.SyntaxTB.has_colors
2241 + IPython.core.ultratb.SyntaxTB.has_colors
2242 + IPython.core.ultratb.TBTools.has_colors
2242 + IPython.core.ultratb.TBTools.has_colors
2243 + IPython.core.ultratb.VerboseTB.has_colors
2243 + IPython.core.ultratb.VerboseTB.has_colors
2244 + IPython.terminal.debugger.TerminalPdb.do_interact
2244 + IPython.terminal.debugger.TerminalPdb.do_interact
2245 + IPython.terminal.debugger.TerminalPdb.precmd
2245 + IPython.terminal.debugger.TerminalPdb.precmd
2246
2246
2247 The following attribute/methods have been removed::
2247 The following attribute/methods have been removed::
2248
2248
2249 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
2249 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
2250 - IPython.core.ultratb.AutoFormattedTB.format_records
2250 - IPython.core.ultratb.AutoFormattedTB.format_records
2251 - IPython.core.ultratb.ColorTB.format_records
2251 - IPython.core.ultratb.ColorTB.format_records
2252 - IPython.core.ultratb.FormattedTB.format_records
2252 - IPython.core.ultratb.FormattedTB.format_records
2253 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
2253 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
2254 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
2254 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
2255 - IPython.terminal.embed.InteractiveShellEmbed.write
2255 - IPython.terminal.embed.InteractiveShellEmbed.write
2256 - IPython.terminal.embed.InteractiveShellEmbed.write_err
2256 - IPython.terminal.embed.InteractiveShellEmbed.write_err
2257 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
2257 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
2258 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
2258 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
2259 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
2259 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
2260 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
2260 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
2261 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
2261 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
2262 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
2262 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
2263 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
2263 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
2264 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
2264 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
2265
2265
2266 ------
2266 ------
2267
2267
2268 .. [1] If this make you incomfortable feel free to not use IPython 8.23.
2268 .. [1] If this make you incomfortable feel free to not use IPython 8.23.
General Comments 0
You need to be logged in to leave comments. Login now