##// END OF EJS Templates
Allow to dispatch getting documentation on objects. (#13975)...
Matthias Bussonnier -
r28201:d52bf622 merge
parent child Browse files
Show More
@@ -1,3898 +1,3907 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13
13
14 import abc
14 import abc
15 import ast
15 import ast
16 import atexit
16 import atexit
17 import bdb
17 import bdb
18 import builtins as builtin_mod
18 import builtins as builtin_mod
19 import functools
19 import functools
20 import inspect
20 import inspect
21 import os
21 import os
22 import re
22 import re
23 import runpy
23 import runpy
24 import subprocess
24 import subprocess
25 import sys
25 import sys
26 import tempfile
26 import tempfile
27 import traceback
27 import traceback
28 import types
28 import types
29 import warnings
29 import warnings
30 from ast import stmt
30 from ast import stmt
31 from io import open as io_open
31 from io import open as io_open
32 from logging import error
32 from logging import error
33 from pathlib import Path
33 from pathlib import Path
34 from typing import Callable
34 from typing import Callable
35 from typing import List as ListType, Dict as DictType, Any as AnyType
35 from typing import List as ListType, Dict as DictType, Any as AnyType
36 from typing import Optional, Sequence, Tuple
36 from typing import Optional, Sequence, Tuple
37 from warnings import warn
37 from warnings import warn
38
38
39 from pickleshare import PickleShareDB
39 from pickleshare import PickleShareDB
40 from tempfile import TemporaryDirectory
40 from tempfile import TemporaryDirectory
41 from traitlets import (
41 from traitlets import (
42 Any,
42 Any,
43 Bool,
43 Bool,
44 CaselessStrEnum,
44 CaselessStrEnum,
45 Dict,
45 Dict,
46 Enum,
46 Enum,
47 Instance,
47 Instance,
48 Integer,
48 Integer,
49 List,
49 List,
50 Type,
50 Type,
51 Unicode,
51 Unicode,
52 default,
52 default,
53 observe,
53 observe,
54 validate,
54 validate,
55 )
55 )
56 from traitlets.config.configurable import SingletonConfigurable
56 from traitlets.config.configurable import SingletonConfigurable
57 from traitlets.utils.importstring import import_item
57 from traitlets.utils.importstring import import_item
58
58
59 import IPython.core.hooks
59 import IPython.core.hooks
60 from IPython.core import magic, oinspect, page, prefilter, ultratb
60 from IPython.core import magic, oinspect, page, prefilter, ultratb
61 from IPython.core.alias import Alias, AliasManager
61 from IPython.core.alias import Alias, AliasManager
62 from IPython.core.autocall import ExitAutocall
62 from IPython.core.autocall import ExitAutocall
63 from IPython.core.builtin_trap import BuiltinTrap
63 from IPython.core.builtin_trap import BuiltinTrap
64 from IPython.core.compilerop import CachingCompiler
64 from IPython.core.compilerop import CachingCompiler
65 from IPython.core.debugger import InterruptiblePdb
65 from IPython.core.debugger import InterruptiblePdb
66 from IPython.core.display_trap import DisplayTrap
66 from IPython.core.display_trap import DisplayTrap
67 from IPython.core.displayhook import DisplayHook
67 from IPython.core.displayhook import DisplayHook
68 from IPython.core.displaypub import DisplayPublisher
68 from IPython.core.displaypub import DisplayPublisher
69 from IPython.core.error import InputRejected, UsageError
69 from IPython.core.error import InputRejected, UsageError
70 from IPython.core.events import EventManager, available_events
70 from IPython.core.events import EventManager, available_events
71 from IPython.core.extensions import ExtensionManager
71 from IPython.core.extensions import ExtensionManager
72 from IPython.core.formatters import DisplayFormatter
72 from IPython.core.formatters import DisplayFormatter
73 from IPython.core.history import HistoryManager
73 from IPython.core.history import HistoryManager
74 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
74 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
75 from IPython.core.logger import Logger
75 from IPython.core.logger import Logger
76 from IPython.core.macro import Macro
76 from IPython.core.macro import Macro
77 from IPython.core.payload import PayloadManager
77 from IPython.core.payload import PayloadManager
78 from IPython.core.prefilter import PrefilterManager
78 from IPython.core.prefilter import PrefilterManager
79 from IPython.core.profiledir import ProfileDir
79 from IPython.core.profiledir import ProfileDir
80 from IPython.core.usage import default_banner
80 from IPython.core.usage import default_banner
81 from IPython.display import display
81 from IPython.display import display
82 from IPython.paths import get_ipython_dir
82 from IPython.paths import get_ipython_dir
83 from IPython.testing.skipdoctest import skip_doctest
83 from IPython.testing.skipdoctest import skip_doctest
84 from IPython.utils import PyColorize, io, openpy, py3compat
84 from IPython.utils import PyColorize, io, openpy, py3compat
85 from IPython.utils.decorators import undoc
85 from IPython.utils.decorators import undoc
86 from IPython.utils.io import ask_yes_no
86 from IPython.utils.io import ask_yes_no
87 from IPython.utils.ipstruct import Struct
87 from IPython.utils.ipstruct import Struct
88 from IPython.utils.path import ensure_dir_exists, get_home_dir, get_py_filename
88 from IPython.utils.path import ensure_dir_exists, get_home_dir, get_py_filename
89 from IPython.utils.process import getoutput, system
89 from IPython.utils.process import getoutput, system
90 from IPython.utils.strdispatch import StrDispatch
90 from IPython.utils.strdispatch import StrDispatch
91 from IPython.utils.syspathcontext import prepended_to_syspath
91 from IPython.utils.syspathcontext import prepended_to_syspath
92 from IPython.utils.text import DollarFormatter, LSString, SList, format_screen
92 from IPython.utils.text import DollarFormatter, LSString, SList, format_screen
93 from IPython.core.oinspect import OInfo
93 from IPython.core.oinspect import OInfo
94
94
95
95
96 sphinxify: Optional[Callable]
96 sphinxify: Optional[Callable]
97
97
98 try:
98 try:
99 import docrepr.sphinxify as sphx
99 import docrepr.sphinxify as sphx
100
100
101 def sphinxify(oinfo):
101 def sphinxify(oinfo):
102 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
102 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
103
103
104 def sphinxify_docstring(docstring):
104 def sphinxify_docstring(docstring):
105 with TemporaryDirectory() as dirname:
105 with TemporaryDirectory() as dirname:
106 return {
106 return {
107 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
107 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
108 "text/plain": docstring,
108 "text/plain": docstring,
109 }
109 }
110
110
111 return sphinxify_docstring
111 return sphinxify_docstring
112 except ImportError:
112 except ImportError:
113 sphinxify = None
113 sphinxify = None
114
114
115
115
116 class ProvisionalWarning(DeprecationWarning):
116 class ProvisionalWarning(DeprecationWarning):
117 """
117 """
118 Warning class for unstable features
118 Warning class for unstable features
119 """
119 """
120 pass
120 pass
121
121
122 from ast import Module
122 from ast import Module
123
123
124 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
124 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
125 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
125 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
126
126
127 #-----------------------------------------------------------------------------
127 #-----------------------------------------------------------------------------
128 # Await Helpers
128 # Await Helpers
129 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
130
130
131 # we still need to run things using the asyncio eventloop, but there is no
131 # we still need to run things using the asyncio eventloop, but there is no
132 # async integration
132 # async integration
133 from .async_helpers import (
133 from .async_helpers import (
134 _asyncio_runner,
134 _asyncio_runner,
135 _curio_runner,
135 _curio_runner,
136 _pseudo_sync_runner,
136 _pseudo_sync_runner,
137 _should_be_async,
137 _should_be_async,
138 _trio_runner,
138 _trio_runner,
139 )
139 )
140
140
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142 # Globals
142 # Globals
143 #-----------------------------------------------------------------------------
143 #-----------------------------------------------------------------------------
144
144
145 # compiled regexps for autoindent management
145 # compiled regexps for autoindent management
146 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
146 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
147
147
148 #-----------------------------------------------------------------------------
148 #-----------------------------------------------------------------------------
149 # Utilities
149 # Utilities
150 #-----------------------------------------------------------------------------
150 #-----------------------------------------------------------------------------
151
151
152
152
153 def is_integer_string(s: str):
153 def is_integer_string(s: str):
154 """
154 """
155 Variant of "str.isnumeric()" that allow negative values and other ints.
155 Variant of "str.isnumeric()" that allow negative values and other ints.
156 """
156 """
157 try:
157 try:
158 int(s)
158 int(s)
159 return True
159 return True
160 except ValueError:
160 except ValueError:
161 return False
161 return False
162 raise ValueError("Unexpected error")
162 raise ValueError("Unexpected error")
163
163
164
164
165 @undoc
165 @undoc
166 def softspace(file, newvalue):
166 def softspace(file, newvalue):
167 """Copied from code.py, to remove the dependency"""
167 """Copied from code.py, to remove the dependency"""
168
168
169 oldvalue = 0
169 oldvalue = 0
170 try:
170 try:
171 oldvalue = file.softspace
171 oldvalue = file.softspace
172 except AttributeError:
172 except AttributeError:
173 pass
173 pass
174 try:
174 try:
175 file.softspace = newvalue
175 file.softspace = newvalue
176 except (AttributeError, TypeError):
176 except (AttributeError, TypeError):
177 # "attribute-less object" or "read-only attributes"
177 # "attribute-less object" or "read-only attributes"
178 pass
178 pass
179 return oldvalue
179 return oldvalue
180
180
181 @undoc
181 @undoc
182 def no_op(*a, **kw):
182 def no_op(*a, **kw):
183 pass
183 pass
184
184
185
185
186 class SpaceInInput(Exception): pass
186 class SpaceInInput(Exception): pass
187
187
188
188
189 class SeparateUnicode(Unicode):
189 class SeparateUnicode(Unicode):
190 r"""A Unicode subclass to validate separate_in, separate_out, etc.
190 r"""A Unicode subclass to validate separate_in, separate_out, etc.
191
191
192 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
192 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
193 """
193 """
194
194
195 def validate(self, obj, value):
195 def validate(self, obj, value):
196 if value == '0': value = ''
196 if value == '0': value = ''
197 value = value.replace('\\n','\n')
197 value = value.replace('\\n','\n')
198 return super(SeparateUnicode, self).validate(obj, value)
198 return super(SeparateUnicode, self).validate(obj, value)
199
199
200
200
201 @undoc
201 @undoc
202 class DummyMod(object):
202 class DummyMod(object):
203 """A dummy module used for IPython's interactive module when
203 """A dummy module used for IPython's interactive module when
204 a namespace must be assigned to the module's __dict__."""
204 a namespace must be assigned to the module's __dict__."""
205 __spec__ = None
205 __spec__ = None
206
206
207
207
208 class ExecutionInfo(object):
208 class ExecutionInfo(object):
209 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
209 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
210
210
211 Stores information about what is going to happen.
211 Stores information about what is going to happen.
212 """
212 """
213 raw_cell = None
213 raw_cell = None
214 store_history = False
214 store_history = False
215 silent = False
215 silent = False
216 shell_futures = True
216 shell_futures = True
217 cell_id = None
217 cell_id = None
218
218
219 def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id):
219 def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id):
220 self.raw_cell = raw_cell
220 self.raw_cell = raw_cell
221 self.store_history = store_history
221 self.store_history = store_history
222 self.silent = silent
222 self.silent = silent
223 self.shell_futures = shell_futures
223 self.shell_futures = shell_futures
224 self.cell_id = cell_id
224 self.cell_id = cell_id
225
225
226 def __repr__(self):
226 def __repr__(self):
227 name = self.__class__.__qualname__
227 name = self.__class__.__qualname__
228 raw_cell = (
228 raw_cell = (
229 (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell
229 (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell
230 )
230 )
231 return (
231 return (
232 '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>'
232 '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>'
233 % (
233 % (
234 name,
234 name,
235 id(self),
235 id(self),
236 raw_cell,
236 raw_cell,
237 self.store_history,
237 self.store_history,
238 self.silent,
238 self.silent,
239 self.shell_futures,
239 self.shell_futures,
240 self.cell_id,
240 self.cell_id,
241 )
241 )
242 )
242 )
243
243
244
244
245 class ExecutionResult(object):
245 class ExecutionResult(object):
246 """The result of a call to :meth:`InteractiveShell.run_cell`
246 """The result of a call to :meth:`InteractiveShell.run_cell`
247
247
248 Stores information about what took place.
248 Stores information about what took place.
249 """
249 """
250 execution_count = None
250 execution_count = None
251 error_before_exec = None
251 error_before_exec = None
252 error_in_exec: Optional[BaseException] = None
252 error_in_exec: Optional[BaseException] = None
253 info = None
253 info = None
254 result = None
254 result = None
255
255
256 def __init__(self, info):
256 def __init__(self, info):
257 self.info = info
257 self.info = info
258
258
259 @property
259 @property
260 def success(self):
260 def success(self):
261 return (self.error_before_exec is None) and (self.error_in_exec is None)
261 return (self.error_before_exec is None) and (self.error_in_exec is None)
262
262
263 def raise_error(self):
263 def raise_error(self):
264 """Reraises error if `success` is `False`, otherwise does nothing"""
264 """Reraises error if `success` is `False`, otherwise does nothing"""
265 if self.error_before_exec is not None:
265 if self.error_before_exec is not None:
266 raise self.error_before_exec
266 raise self.error_before_exec
267 if self.error_in_exec is not None:
267 if self.error_in_exec is not None:
268 raise self.error_in_exec
268 raise self.error_in_exec
269
269
270 def __repr__(self):
270 def __repr__(self):
271 name = self.__class__.__qualname__
271 name = self.__class__.__qualname__
272 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
272 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
273 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
273 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
274
274
275 @functools.wraps(io_open)
275 @functools.wraps(io_open)
276 def _modified_open(file, *args, **kwargs):
276 def _modified_open(file, *args, **kwargs):
277 if file in {0, 1, 2}:
277 if file in {0, 1, 2}:
278 raise ValueError(
278 raise ValueError(
279 f"IPython won't let you open fd={file} by default "
279 f"IPython won't let you open fd={file} by default "
280 "as it is likely to crash IPython. If you know what you are doing, "
280 "as it is likely to crash IPython. If you know what you are doing, "
281 "you can use builtins' open."
281 "you can use builtins' open."
282 )
282 )
283
283
284 return io_open(file, *args, **kwargs)
284 return io_open(file, *args, **kwargs)
285
285
286 class InteractiveShell(SingletonConfigurable):
286 class InteractiveShell(SingletonConfigurable):
287 """An enhanced, interactive shell for Python."""
287 """An enhanced, interactive shell for Python."""
288
288
289 _instance = None
289 _instance = None
290
290
291 ast_transformers = List([], help=
291 ast_transformers = List([], help=
292 """
292 """
293 A list of ast.NodeTransformer subclass instances, which will be applied
293 A list of ast.NodeTransformer subclass instances, which will be applied
294 to user input before code is run.
294 to user input before code is run.
295 """
295 """
296 ).tag(config=True)
296 ).tag(config=True)
297
297
298 autocall = Enum((0,1,2), default_value=0, help=
298 autocall = Enum((0,1,2), default_value=0, help=
299 """
299 """
300 Make IPython automatically call any callable object even if you didn't
300 Make IPython automatically call any callable object even if you didn't
301 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
301 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
302 automatically. The value can be '0' to disable the feature, '1' for
302 automatically. The value can be '0' to disable the feature, '1' for
303 'smart' autocall, where it is not applied if there are no more
303 'smart' autocall, where it is not applied if there are no more
304 arguments on the line, and '2' for 'full' autocall, where all callable
304 arguments on the line, and '2' for 'full' autocall, where all callable
305 objects are automatically called (even if no arguments are present).
305 objects are automatically called (even if no arguments are present).
306 """
306 """
307 ).tag(config=True)
307 ).tag(config=True)
308
308
309 autoindent = Bool(True, help=
309 autoindent = Bool(True, help=
310 """
310 """
311 Autoindent IPython code entered interactively.
311 Autoindent IPython code entered interactively.
312 """
312 """
313 ).tag(config=True)
313 ).tag(config=True)
314
314
315 autoawait = Bool(True, help=
315 autoawait = Bool(True, help=
316 """
316 """
317 Automatically run await statement in the top level repl.
317 Automatically run await statement in the top level repl.
318 """
318 """
319 ).tag(config=True)
319 ).tag(config=True)
320
320
321 loop_runner_map ={
321 loop_runner_map ={
322 'asyncio':(_asyncio_runner, True),
322 'asyncio':(_asyncio_runner, True),
323 'curio':(_curio_runner, True),
323 'curio':(_curio_runner, True),
324 'trio':(_trio_runner, True),
324 'trio':(_trio_runner, True),
325 'sync': (_pseudo_sync_runner, False)
325 'sync': (_pseudo_sync_runner, False)
326 }
326 }
327
327
328 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
328 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
329 allow_none=True,
329 allow_none=True,
330 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
330 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
331 ).tag(config=True)
331 ).tag(config=True)
332
332
333 @default('loop_runner')
333 @default('loop_runner')
334 def _default_loop_runner(self):
334 def _default_loop_runner(self):
335 return import_item("IPython.core.interactiveshell._asyncio_runner")
335 return import_item("IPython.core.interactiveshell._asyncio_runner")
336
336
337 @validate('loop_runner')
337 @validate('loop_runner')
338 def _import_runner(self, proposal):
338 def _import_runner(self, proposal):
339 if isinstance(proposal.value, str):
339 if isinstance(proposal.value, str):
340 if proposal.value in self.loop_runner_map:
340 if proposal.value in self.loop_runner_map:
341 runner, autoawait = self.loop_runner_map[proposal.value]
341 runner, autoawait = self.loop_runner_map[proposal.value]
342 self.autoawait = autoawait
342 self.autoawait = autoawait
343 return runner
343 return runner
344 runner = import_item(proposal.value)
344 runner = import_item(proposal.value)
345 if not callable(runner):
345 if not callable(runner):
346 raise ValueError('loop_runner must be callable')
346 raise ValueError('loop_runner must be callable')
347 return runner
347 return runner
348 if not callable(proposal.value):
348 if not callable(proposal.value):
349 raise ValueError('loop_runner must be callable')
349 raise ValueError('loop_runner must be callable')
350 return proposal.value
350 return proposal.value
351
351
352 automagic = Bool(True, help=
352 automagic = Bool(True, help=
353 """
353 """
354 Enable magic commands to be called without the leading %.
354 Enable magic commands to be called without the leading %.
355 """
355 """
356 ).tag(config=True)
356 ).tag(config=True)
357
357
358 banner1 = Unicode(default_banner,
358 banner1 = Unicode(default_banner,
359 help="""The part of the banner to be printed before the profile"""
359 help="""The part of the banner to be printed before the profile"""
360 ).tag(config=True)
360 ).tag(config=True)
361 banner2 = Unicode('',
361 banner2 = Unicode('',
362 help="""The part of the banner to be printed after the profile"""
362 help="""The part of the banner to be printed after the profile"""
363 ).tag(config=True)
363 ).tag(config=True)
364
364
365 cache_size = Integer(1000, help=
365 cache_size = Integer(1000, help=
366 """
366 """
367 Set the size of the output cache. The default is 1000, you can
367 Set the size of the output cache. The default is 1000, you can
368 change it permanently in your config file. Setting it to 0 completely
368 change it permanently in your config file. Setting it to 0 completely
369 disables the caching system, and the minimum value accepted is 3 (if
369 disables the caching system, and the minimum value accepted is 3 (if
370 you provide a value less than 3, it is reset to 0 and a warning is
370 you provide a value less than 3, it is reset to 0 and a warning is
371 issued). This limit is defined because otherwise you'll spend more
371 issued). This limit is defined because otherwise you'll spend more
372 time re-flushing a too small cache than working
372 time re-flushing a too small cache than working
373 """
373 """
374 ).tag(config=True)
374 ).tag(config=True)
375 color_info = Bool(True, help=
375 color_info = Bool(True, help=
376 """
376 """
377 Use colors for displaying information about objects. Because this
377 Use colors for displaying information about objects. Because this
378 information is passed through a pager (like 'less'), and some pagers
378 information is passed through a pager (like 'less'), and some pagers
379 get confused with color codes, this capability can be turned off.
379 get confused with color codes, this capability can be turned off.
380 """
380 """
381 ).tag(config=True)
381 ).tag(config=True)
382 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
382 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
383 default_value='Neutral',
383 default_value='Neutral',
384 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
384 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
385 ).tag(config=True)
385 ).tag(config=True)
386 debug = Bool(False).tag(config=True)
386 debug = Bool(False).tag(config=True)
387 disable_failing_post_execute = Bool(False,
387 disable_failing_post_execute = Bool(False,
388 help="Don't call post-execute functions that have failed in the past."
388 help="Don't call post-execute functions that have failed in the past."
389 ).tag(config=True)
389 ).tag(config=True)
390 display_formatter = Instance(DisplayFormatter, allow_none=True)
390 display_formatter = Instance(DisplayFormatter, allow_none=True)
391 displayhook_class = Type(DisplayHook)
391 displayhook_class = Type(DisplayHook)
392 display_pub_class = Type(DisplayPublisher)
392 display_pub_class = Type(DisplayPublisher)
393 compiler_class = Type(CachingCompiler)
393 compiler_class = Type(CachingCompiler)
394 inspector_class = Type(
394 inspector_class = Type(
395 oinspect.Inspector, help="Class to use to instantiate the shell inspector"
395 oinspect.Inspector, help="Class to use to instantiate the shell inspector"
396 ).tag(config=True)
396 ).tag(config=True)
397
397
398 sphinxify_docstring = Bool(False, help=
398 sphinxify_docstring = Bool(False, help=
399 """
399 """
400 Enables rich html representation of docstrings. (This requires the
400 Enables rich html representation of docstrings. (This requires the
401 docrepr module).
401 docrepr module).
402 """).tag(config=True)
402 """).tag(config=True)
403
403
404 @observe("sphinxify_docstring")
404 @observe("sphinxify_docstring")
405 def _sphinxify_docstring_changed(self, change):
405 def _sphinxify_docstring_changed(self, change):
406 if change['new']:
406 if change['new']:
407 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
407 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
408
408
409 enable_html_pager = Bool(False, help=
409 enable_html_pager = Bool(False, help=
410 """
410 """
411 (Provisional API) enables html representation in mime bundles sent
411 (Provisional API) enables html representation in mime bundles sent
412 to pagers.
412 to pagers.
413 """).tag(config=True)
413 """).tag(config=True)
414
414
415 @observe("enable_html_pager")
415 @observe("enable_html_pager")
416 def _enable_html_pager_changed(self, change):
416 def _enable_html_pager_changed(self, change):
417 if change['new']:
417 if change['new']:
418 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
418 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
419
419
420 data_pub_class = None
420 data_pub_class = None
421
421
422 exit_now = Bool(False)
422 exit_now = Bool(False)
423 exiter = Instance(ExitAutocall)
423 exiter = Instance(ExitAutocall)
424 @default('exiter')
424 @default('exiter')
425 def _exiter_default(self):
425 def _exiter_default(self):
426 return ExitAutocall(self)
426 return ExitAutocall(self)
427 # Monotonically increasing execution counter
427 # Monotonically increasing execution counter
428 execution_count = Integer(1)
428 execution_count = Integer(1)
429 filename = Unicode("<ipython console>")
429 filename = Unicode("<ipython console>")
430 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
430 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
431
431
432 # Used to transform cells before running them, and check whether code is complete
432 # Used to transform cells before running them, and check whether code is complete
433 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
433 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
434 ())
434 ())
435
435
436 @property
436 @property
437 def input_transformers_cleanup(self):
437 def input_transformers_cleanup(self):
438 return self.input_transformer_manager.cleanup_transforms
438 return self.input_transformer_manager.cleanup_transforms
439
439
440 input_transformers_post = List([],
440 input_transformers_post = List([],
441 help="A list of string input transformers, to be applied after IPython's "
441 help="A list of string input transformers, to be applied after IPython's "
442 "own input transformations."
442 "own input transformations."
443 )
443 )
444
444
445 @property
445 @property
446 def input_splitter(self):
446 def input_splitter(self):
447 """Make this available for backward compatibility (pre-7.0 release) with existing code.
447 """Make this available for backward compatibility (pre-7.0 release) with existing code.
448
448
449 For example, ipykernel ipykernel currently uses
449 For example, ipykernel ipykernel currently uses
450 `shell.input_splitter.check_complete`
450 `shell.input_splitter.check_complete`
451 """
451 """
452 from warnings import warn
452 from warnings import warn
453 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
453 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
454 DeprecationWarning, stacklevel=2
454 DeprecationWarning, stacklevel=2
455 )
455 )
456 return self.input_transformer_manager
456 return self.input_transformer_manager
457
457
458 logstart = Bool(False, help=
458 logstart = Bool(False, help=
459 """
459 """
460 Start logging to the default log file in overwrite mode.
460 Start logging to the default log file in overwrite mode.
461 Use `logappend` to specify a log file to **append** logs to.
461 Use `logappend` to specify a log file to **append** logs to.
462 """
462 """
463 ).tag(config=True)
463 ).tag(config=True)
464 logfile = Unicode('', help=
464 logfile = Unicode('', help=
465 """
465 """
466 The name of the logfile to use.
466 The name of the logfile to use.
467 """
467 """
468 ).tag(config=True)
468 ).tag(config=True)
469 logappend = Unicode('', help=
469 logappend = Unicode('', help=
470 """
470 """
471 Start logging to the given file in append mode.
471 Start logging to the given file in append mode.
472 Use `logfile` to specify a log file to **overwrite** logs to.
472 Use `logfile` to specify a log file to **overwrite** logs to.
473 """
473 """
474 ).tag(config=True)
474 ).tag(config=True)
475 object_info_string_level = Enum((0,1,2), default_value=0,
475 object_info_string_level = Enum((0,1,2), default_value=0,
476 ).tag(config=True)
476 ).tag(config=True)
477 pdb = Bool(False, help=
477 pdb = Bool(False, help=
478 """
478 """
479 Automatically call the pdb debugger after every exception.
479 Automatically call the pdb debugger after every exception.
480 """
480 """
481 ).tag(config=True)
481 ).tag(config=True)
482 display_page = Bool(False,
482 display_page = Bool(False,
483 help="""If True, anything that would be passed to the pager
483 help="""If True, anything that would be passed to the pager
484 will be displayed as regular output instead."""
484 will be displayed as regular output instead."""
485 ).tag(config=True)
485 ).tag(config=True)
486
486
487
487
488 show_rewritten_input = Bool(True,
488 show_rewritten_input = Bool(True,
489 help="Show rewritten input, e.g. for autocall."
489 help="Show rewritten input, e.g. for autocall."
490 ).tag(config=True)
490 ).tag(config=True)
491
491
492 quiet = Bool(False).tag(config=True)
492 quiet = Bool(False).tag(config=True)
493
493
494 history_length = Integer(10000,
494 history_length = Integer(10000,
495 help='Total length of command history'
495 help='Total length of command history'
496 ).tag(config=True)
496 ).tag(config=True)
497
497
498 history_load_length = Integer(1000, help=
498 history_load_length = Integer(1000, help=
499 """
499 """
500 The number of saved history entries to be loaded
500 The number of saved history entries to be loaded
501 into the history buffer at startup.
501 into the history buffer at startup.
502 """
502 """
503 ).tag(config=True)
503 ).tag(config=True)
504
504
505 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
505 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
506 default_value='last_expr',
506 default_value='last_expr',
507 help="""
507 help="""
508 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
508 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
509 which nodes should be run interactively (displaying output from expressions).
509 which nodes should be run interactively (displaying output from expressions).
510 """
510 """
511 ).tag(config=True)
511 ).tag(config=True)
512
512
513 warn_venv = Bool(
513 warn_venv = Bool(
514 True,
514 True,
515 help="Warn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).",
515 help="Warn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).",
516 ).tag(config=True)
516 ).tag(config=True)
517
517
518 # TODO: this part of prompt management should be moved to the frontends.
518 # TODO: this part of prompt management should be moved to the frontends.
519 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
519 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
520 separate_in = SeparateUnicode('\n').tag(config=True)
520 separate_in = SeparateUnicode('\n').tag(config=True)
521 separate_out = SeparateUnicode('').tag(config=True)
521 separate_out = SeparateUnicode('').tag(config=True)
522 separate_out2 = SeparateUnicode('').tag(config=True)
522 separate_out2 = SeparateUnicode('').tag(config=True)
523 wildcards_case_sensitive = Bool(True).tag(config=True)
523 wildcards_case_sensitive = Bool(True).tag(config=True)
524 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
524 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
525 default_value='Context',
525 default_value='Context',
526 help="Switch modes for the IPython exception handlers."
526 help="Switch modes for the IPython exception handlers."
527 ).tag(config=True)
527 ).tag(config=True)
528
528
529 # Subcomponents of InteractiveShell
529 # Subcomponents of InteractiveShell
530 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
530 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
531 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
531 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
532 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
532 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
533 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
533 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
534 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
534 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
535 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
535 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
536 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
536 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
537 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
537 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
538
538
539 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
539 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
540 @property
540 @property
541 def profile(self):
541 def profile(self):
542 if self.profile_dir is not None:
542 if self.profile_dir is not None:
543 name = os.path.basename(self.profile_dir.location)
543 name = os.path.basename(self.profile_dir.location)
544 return name.replace('profile_','')
544 return name.replace('profile_','')
545
545
546
546
547 # Private interface
547 # Private interface
548 _post_execute = Dict()
548 _post_execute = Dict()
549
549
550 # Tracks any GUI loop loaded for pylab
550 # Tracks any GUI loop loaded for pylab
551 pylab_gui_select = None
551 pylab_gui_select = None
552
552
553 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
553 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
554
554
555 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
555 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
556
556
557 def __init__(self, ipython_dir=None, profile_dir=None,
557 def __init__(self, ipython_dir=None, profile_dir=None,
558 user_module=None, user_ns=None,
558 user_module=None, user_ns=None,
559 custom_exceptions=((), None), **kwargs):
559 custom_exceptions=((), None), **kwargs):
560 # This is where traits with a config_key argument are updated
560 # This is where traits with a config_key argument are updated
561 # from the values on config.
561 # from the values on config.
562 super(InteractiveShell, self).__init__(**kwargs)
562 super(InteractiveShell, self).__init__(**kwargs)
563 if 'PromptManager' in self.config:
563 if 'PromptManager' in self.config:
564 warn('As of IPython 5.0 `PromptManager` config will have no effect'
564 warn('As of IPython 5.0 `PromptManager` config will have no effect'
565 ' and has been replaced by TerminalInteractiveShell.prompts_class')
565 ' and has been replaced by TerminalInteractiveShell.prompts_class')
566 self.configurables = [self]
566 self.configurables = [self]
567
567
568 # These are relatively independent and stateless
568 # These are relatively independent and stateless
569 self.init_ipython_dir(ipython_dir)
569 self.init_ipython_dir(ipython_dir)
570 self.init_profile_dir(profile_dir)
570 self.init_profile_dir(profile_dir)
571 self.init_instance_attrs()
571 self.init_instance_attrs()
572 self.init_environment()
572 self.init_environment()
573
573
574 # Check if we're in a virtualenv, and set up sys.path.
574 # Check if we're in a virtualenv, and set up sys.path.
575 self.init_virtualenv()
575 self.init_virtualenv()
576
576
577 # Create namespaces (user_ns, user_global_ns, etc.)
577 # Create namespaces (user_ns, user_global_ns, etc.)
578 self.init_create_namespaces(user_module, user_ns)
578 self.init_create_namespaces(user_module, user_ns)
579 # This has to be done after init_create_namespaces because it uses
579 # This has to be done after init_create_namespaces because it uses
580 # something in self.user_ns, but before init_sys_modules, which
580 # something in self.user_ns, but before init_sys_modules, which
581 # is the first thing to modify sys.
581 # is the first thing to modify sys.
582 # TODO: When we override sys.stdout and sys.stderr before this class
582 # TODO: When we override sys.stdout and sys.stderr before this class
583 # is created, we are saving the overridden ones here. Not sure if this
583 # is created, we are saving the overridden ones here. Not sure if this
584 # is what we want to do.
584 # is what we want to do.
585 self.save_sys_module_state()
585 self.save_sys_module_state()
586 self.init_sys_modules()
586 self.init_sys_modules()
587
587
588 # While we're trying to have each part of the code directly access what
588 # While we're trying to have each part of the code directly access what
589 # it needs without keeping redundant references to objects, we have too
589 # it needs without keeping redundant references to objects, we have too
590 # much legacy code that expects ip.db to exist.
590 # much legacy code that expects ip.db to exist.
591 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
591 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
592
592
593 self.init_history()
593 self.init_history()
594 self.init_encoding()
594 self.init_encoding()
595 self.init_prefilter()
595 self.init_prefilter()
596
596
597 self.init_syntax_highlighting()
597 self.init_syntax_highlighting()
598 self.init_hooks()
598 self.init_hooks()
599 self.init_events()
599 self.init_events()
600 self.init_pushd_popd_magic()
600 self.init_pushd_popd_magic()
601 self.init_user_ns()
601 self.init_user_ns()
602 self.init_logger()
602 self.init_logger()
603 self.init_builtins()
603 self.init_builtins()
604
604
605 # The following was in post_config_initialization
605 # The following was in post_config_initialization
606 self.init_inspector()
606 self.init_inspector()
607 self.raw_input_original = input
607 self.raw_input_original = input
608 self.init_completer()
608 self.init_completer()
609 # TODO: init_io() needs to happen before init_traceback handlers
609 # TODO: init_io() needs to happen before init_traceback handlers
610 # because the traceback handlers hardcode the stdout/stderr streams.
610 # because the traceback handlers hardcode the stdout/stderr streams.
611 # This logic in in debugger.Pdb and should eventually be changed.
611 # This logic in in debugger.Pdb and should eventually be changed.
612 self.init_io()
612 self.init_io()
613 self.init_traceback_handlers(custom_exceptions)
613 self.init_traceback_handlers(custom_exceptions)
614 self.init_prompts()
614 self.init_prompts()
615 self.init_display_formatter()
615 self.init_display_formatter()
616 self.init_display_pub()
616 self.init_display_pub()
617 self.init_data_pub()
617 self.init_data_pub()
618 self.init_displayhook()
618 self.init_displayhook()
619 self.init_magics()
619 self.init_magics()
620 self.init_alias()
620 self.init_alias()
621 self.init_logstart()
621 self.init_logstart()
622 self.init_pdb()
622 self.init_pdb()
623 self.init_extension_manager()
623 self.init_extension_manager()
624 self.init_payload()
624 self.init_payload()
625 self.events.trigger('shell_initialized', self)
625 self.events.trigger('shell_initialized', self)
626 atexit.register(self.atexit_operations)
626 atexit.register(self.atexit_operations)
627
627
628 # The trio runner is used for running Trio in the foreground thread. It
628 # The trio runner is used for running Trio in the foreground thread. It
629 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
629 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
630 # which calls `trio.run()` for every cell. This runner runs all cells
630 # which calls `trio.run()` for every cell. This runner runs all cells
631 # inside a single Trio event loop. If used, it is set from
631 # inside a single Trio event loop. If used, it is set from
632 # `ipykernel.kernelapp`.
632 # `ipykernel.kernelapp`.
633 self.trio_runner = None
633 self.trio_runner = None
634
634
635 def get_ipython(self):
635 def get_ipython(self):
636 """Return the currently running IPython instance."""
636 """Return the currently running IPython instance."""
637 return self
637 return self
638
638
639 #-------------------------------------------------------------------------
639 #-------------------------------------------------------------------------
640 # Trait changed handlers
640 # Trait changed handlers
641 #-------------------------------------------------------------------------
641 #-------------------------------------------------------------------------
642 @observe('ipython_dir')
642 @observe('ipython_dir')
643 def _ipython_dir_changed(self, change):
643 def _ipython_dir_changed(self, change):
644 ensure_dir_exists(change['new'])
644 ensure_dir_exists(change['new'])
645
645
646 def set_autoindent(self,value=None):
646 def set_autoindent(self,value=None):
647 """Set the autoindent flag.
647 """Set the autoindent flag.
648
648
649 If called with no arguments, it acts as a toggle."""
649 If called with no arguments, it acts as a toggle."""
650 if value is None:
650 if value is None:
651 self.autoindent = not self.autoindent
651 self.autoindent = not self.autoindent
652 else:
652 else:
653 self.autoindent = value
653 self.autoindent = value
654
654
655 def set_trio_runner(self, tr):
655 def set_trio_runner(self, tr):
656 self.trio_runner = tr
656 self.trio_runner = tr
657
657
658 #-------------------------------------------------------------------------
658 #-------------------------------------------------------------------------
659 # init_* methods called by __init__
659 # init_* methods called by __init__
660 #-------------------------------------------------------------------------
660 #-------------------------------------------------------------------------
661
661
662 def init_ipython_dir(self, ipython_dir):
662 def init_ipython_dir(self, ipython_dir):
663 if ipython_dir is not None:
663 if ipython_dir is not None:
664 self.ipython_dir = ipython_dir
664 self.ipython_dir = ipython_dir
665 return
665 return
666
666
667 self.ipython_dir = get_ipython_dir()
667 self.ipython_dir = get_ipython_dir()
668
668
669 def init_profile_dir(self, profile_dir):
669 def init_profile_dir(self, profile_dir):
670 if profile_dir is not None:
670 if profile_dir is not None:
671 self.profile_dir = profile_dir
671 self.profile_dir = profile_dir
672 return
672 return
673 self.profile_dir = ProfileDir.create_profile_dir_by_name(
673 self.profile_dir = ProfileDir.create_profile_dir_by_name(
674 self.ipython_dir, "default"
674 self.ipython_dir, "default"
675 )
675 )
676
676
677 def init_instance_attrs(self):
677 def init_instance_attrs(self):
678 self.more = False
678 self.more = False
679
679
680 # command compiler
680 # command compiler
681 self.compile = self.compiler_class()
681 self.compile = self.compiler_class()
682
682
683 # Make an empty namespace, which extension writers can rely on both
683 # Make an empty namespace, which extension writers can rely on both
684 # existing and NEVER being used by ipython itself. This gives them a
684 # existing and NEVER being used by ipython itself. This gives them a
685 # convenient location for storing additional information and state
685 # convenient location for storing additional information and state
686 # their extensions may require, without fear of collisions with other
686 # their extensions may require, without fear of collisions with other
687 # ipython names that may develop later.
687 # ipython names that may develop later.
688 self.meta = Struct()
688 self.meta = Struct()
689
689
690 # Temporary files used for various purposes. Deleted at exit.
690 # Temporary files used for various purposes. Deleted at exit.
691 # The files here are stored with Path from Pathlib
691 # The files here are stored with Path from Pathlib
692 self.tempfiles = []
692 self.tempfiles = []
693 self.tempdirs = []
693 self.tempdirs = []
694
694
695 # keep track of where we started running (mainly for crash post-mortem)
695 # keep track of where we started running (mainly for crash post-mortem)
696 # This is not being used anywhere currently.
696 # This is not being used anywhere currently.
697 self.starting_dir = os.getcwd()
697 self.starting_dir = os.getcwd()
698
698
699 # Indentation management
699 # Indentation management
700 self.indent_current_nsp = 0
700 self.indent_current_nsp = 0
701
701
702 # Dict to track post-execution functions that have been registered
702 # Dict to track post-execution functions that have been registered
703 self._post_execute = {}
703 self._post_execute = {}
704
704
705 def init_environment(self):
705 def init_environment(self):
706 """Any changes we need to make to the user's environment."""
706 """Any changes we need to make to the user's environment."""
707 pass
707 pass
708
708
709 def init_encoding(self):
709 def init_encoding(self):
710 # Get system encoding at startup time. Certain terminals (like Emacs
710 # Get system encoding at startup time. Certain terminals (like Emacs
711 # under Win32 have it set to None, and we need to have a known valid
711 # under Win32 have it set to None, and we need to have a known valid
712 # encoding to use in the raw_input() method
712 # encoding to use in the raw_input() method
713 try:
713 try:
714 self.stdin_encoding = sys.stdin.encoding or 'ascii'
714 self.stdin_encoding = sys.stdin.encoding or 'ascii'
715 except AttributeError:
715 except AttributeError:
716 self.stdin_encoding = 'ascii'
716 self.stdin_encoding = 'ascii'
717
717
718
718
719 @observe('colors')
719 @observe('colors')
720 def init_syntax_highlighting(self, changes=None):
720 def init_syntax_highlighting(self, changes=None):
721 # Python source parser/formatter for syntax highlighting
721 # Python source parser/formatter for syntax highlighting
722 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
722 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
723 self.pycolorize = lambda src: pyformat(src,'str')
723 self.pycolorize = lambda src: pyformat(src,'str')
724
724
725 def refresh_style(self):
725 def refresh_style(self):
726 # No-op here, used in subclass
726 # No-op here, used in subclass
727 pass
727 pass
728
728
729 def init_pushd_popd_magic(self):
729 def init_pushd_popd_magic(self):
730 # for pushd/popd management
730 # for pushd/popd management
731 self.home_dir = get_home_dir()
731 self.home_dir = get_home_dir()
732
732
733 self.dir_stack = []
733 self.dir_stack = []
734
734
735 def init_logger(self):
735 def init_logger(self):
736 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
736 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
737 logmode='rotate')
737 logmode='rotate')
738
738
739 def init_logstart(self):
739 def init_logstart(self):
740 """Initialize logging in case it was requested at the command line.
740 """Initialize logging in case it was requested at the command line.
741 """
741 """
742 if self.logappend:
742 if self.logappend:
743 self.magic('logstart %s append' % self.logappend)
743 self.magic('logstart %s append' % self.logappend)
744 elif self.logfile:
744 elif self.logfile:
745 self.magic('logstart %s' % self.logfile)
745 self.magic('logstart %s' % self.logfile)
746 elif self.logstart:
746 elif self.logstart:
747 self.magic('logstart')
747 self.magic('logstart')
748
748
749
749
750 def init_builtins(self):
750 def init_builtins(self):
751 # A single, static flag that we set to True. Its presence indicates
751 # A single, static flag that we set to True. Its presence indicates
752 # that an IPython shell has been created, and we make no attempts at
752 # that an IPython shell has been created, and we make no attempts at
753 # removing on exit or representing the existence of more than one
753 # removing on exit or representing the existence of more than one
754 # IPython at a time.
754 # IPython at a time.
755 builtin_mod.__dict__['__IPYTHON__'] = True
755 builtin_mod.__dict__['__IPYTHON__'] = True
756 builtin_mod.__dict__['display'] = display
756 builtin_mod.__dict__['display'] = display
757
757
758 self.builtin_trap = BuiltinTrap(shell=self)
758 self.builtin_trap = BuiltinTrap(shell=self)
759
759
760 @observe('colors')
760 @observe('colors')
761 def init_inspector(self, changes=None):
761 def init_inspector(self, changes=None):
762 # Object inspector
762 # Object inspector
763 self.inspector = self.inspector_class(
763 self.inspector = self.inspector_class(
764 oinspect.InspectColors,
764 oinspect.InspectColors,
765 PyColorize.ANSICodeColors,
765 PyColorize.ANSICodeColors,
766 self.colors,
766 self.colors,
767 self.object_info_string_level,
767 self.object_info_string_level,
768 )
768 )
769
769
770 def init_io(self):
770 def init_io(self):
771 # implemented in subclasses, TerminalInteractiveShell does call
771 # implemented in subclasses, TerminalInteractiveShell does call
772 # colorama.init().
772 # colorama.init().
773 pass
773 pass
774
774
775 def init_prompts(self):
775 def init_prompts(self):
776 # Set system prompts, so that scripts can decide if they are running
776 # Set system prompts, so that scripts can decide if they are running
777 # interactively.
777 # interactively.
778 sys.ps1 = 'In : '
778 sys.ps1 = 'In : '
779 sys.ps2 = '...: '
779 sys.ps2 = '...: '
780 sys.ps3 = 'Out: '
780 sys.ps3 = 'Out: '
781
781
782 def init_display_formatter(self):
782 def init_display_formatter(self):
783 self.display_formatter = DisplayFormatter(parent=self)
783 self.display_formatter = DisplayFormatter(parent=self)
784 self.configurables.append(self.display_formatter)
784 self.configurables.append(self.display_formatter)
785
785
786 def init_display_pub(self):
786 def init_display_pub(self):
787 self.display_pub = self.display_pub_class(parent=self, shell=self)
787 self.display_pub = self.display_pub_class(parent=self, shell=self)
788 self.configurables.append(self.display_pub)
788 self.configurables.append(self.display_pub)
789
789
790 def init_data_pub(self):
790 def init_data_pub(self):
791 if not self.data_pub_class:
791 if not self.data_pub_class:
792 self.data_pub = None
792 self.data_pub = None
793 return
793 return
794 self.data_pub = self.data_pub_class(parent=self)
794 self.data_pub = self.data_pub_class(parent=self)
795 self.configurables.append(self.data_pub)
795 self.configurables.append(self.data_pub)
796
796
797 def init_displayhook(self):
797 def init_displayhook(self):
798 # Initialize displayhook, set in/out prompts and printing system
798 # Initialize displayhook, set in/out prompts and printing system
799 self.displayhook = self.displayhook_class(
799 self.displayhook = self.displayhook_class(
800 parent=self,
800 parent=self,
801 shell=self,
801 shell=self,
802 cache_size=self.cache_size,
802 cache_size=self.cache_size,
803 )
803 )
804 self.configurables.append(self.displayhook)
804 self.configurables.append(self.displayhook)
805 # This is a context manager that installs/revmoes the displayhook at
805 # This is a context manager that installs/revmoes the displayhook at
806 # the appropriate time.
806 # the appropriate time.
807 self.display_trap = DisplayTrap(hook=self.displayhook)
807 self.display_trap = DisplayTrap(hook=self.displayhook)
808
808
809 @staticmethod
809 @staticmethod
810 def get_path_links(p: Path):
810 def get_path_links(p: Path):
811 """Gets path links including all symlinks
811 """Gets path links including all symlinks
812
812
813 Examples
813 Examples
814 --------
814 --------
815 In [1]: from IPython.core.interactiveshell import InteractiveShell
815 In [1]: from IPython.core.interactiveshell import InteractiveShell
816
816
817 In [2]: import sys, pathlib
817 In [2]: import sys, pathlib
818
818
819 In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable))
819 In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable))
820
820
821 In [4]: len(paths) == len(set(paths))
821 In [4]: len(paths) == len(set(paths))
822 Out[4]: True
822 Out[4]: True
823
823
824 In [5]: bool(paths)
824 In [5]: bool(paths)
825 Out[5]: True
825 Out[5]: True
826 """
826 """
827 paths = [p]
827 paths = [p]
828 while p.is_symlink():
828 while p.is_symlink():
829 new_path = Path(os.readlink(p))
829 new_path = Path(os.readlink(p))
830 if not new_path.is_absolute():
830 if not new_path.is_absolute():
831 new_path = p.parent / new_path
831 new_path = p.parent / new_path
832 p = new_path
832 p = new_path
833 paths.append(p)
833 paths.append(p)
834 return paths
834 return paths
835
835
836 def init_virtualenv(self):
836 def init_virtualenv(self):
837 """Add the current virtualenv to sys.path so the user can import modules from it.
837 """Add the current virtualenv to sys.path so the user can import modules from it.
838 This isn't perfect: it doesn't use the Python interpreter with which the
838 This isn't perfect: it doesn't use the Python interpreter with which the
839 virtualenv was built, and it ignores the --no-site-packages option. A
839 virtualenv was built, and it ignores the --no-site-packages option. A
840 warning will appear suggesting the user installs IPython in the
840 warning will appear suggesting the user installs IPython in the
841 virtualenv, but for many cases, it probably works well enough.
841 virtualenv, but for many cases, it probably works well enough.
842
842
843 Adapted from code snippets online.
843 Adapted from code snippets online.
844
844
845 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
845 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
846 """
846 """
847 if 'VIRTUAL_ENV' not in os.environ:
847 if 'VIRTUAL_ENV' not in os.environ:
848 # Not in a virtualenv
848 # Not in a virtualenv
849 return
849 return
850 elif os.environ["VIRTUAL_ENV"] == "":
850 elif os.environ["VIRTUAL_ENV"] == "":
851 warn("Virtual env path set to '', please check if this is intended.")
851 warn("Virtual env path set to '', please check if this is intended.")
852 return
852 return
853
853
854 p = Path(sys.executable)
854 p = Path(sys.executable)
855 p_venv = Path(os.environ["VIRTUAL_ENV"])
855 p_venv = Path(os.environ["VIRTUAL_ENV"])
856
856
857 # fallback venv detection:
857 # fallback venv detection:
858 # stdlib venv may symlink sys.executable, so we can't use realpath.
858 # stdlib venv may symlink sys.executable, so we can't use realpath.
859 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
859 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
860 # So we just check every item in the symlink tree (generally <= 3)
860 # So we just check every item in the symlink tree (generally <= 3)
861 paths = self.get_path_links(p)
861 paths = self.get_path_links(p)
862
862
863 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
863 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
864 if p_venv.parts[1] == "cygdrive":
864 if p_venv.parts[1] == "cygdrive":
865 drive_name = p_venv.parts[2]
865 drive_name = p_venv.parts[2]
866 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
866 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
867
867
868 if any(p_venv == p.parents[1] for p in paths):
868 if any(p_venv == p.parents[1] for p in paths):
869 # Our exe is inside or has access to the virtualenv, don't need to do anything.
869 # Our exe is inside or has access to the virtualenv, don't need to do anything.
870 return
870 return
871
871
872 if sys.platform == "win32":
872 if sys.platform == "win32":
873 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
873 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
874 else:
874 else:
875 virtual_env_path = Path(
875 virtual_env_path = Path(
876 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
876 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
877 )
877 )
878 p_ver = sys.version_info[:2]
878 p_ver = sys.version_info[:2]
879
879
880 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
880 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
881 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
881 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
882 if re_m:
882 if re_m:
883 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
883 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
884 if predicted_path.exists():
884 if predicted_path.exists():
885 p_ver = re_m.groups()
885 p_ver = re_m.groups()
886
886
887 virtual_env = str(virtual_env_path).format(*p_ver)
887 virtual_env = str(virtual_env_path).format(*p_ver)
888 if self.warn_venv:
888 if self.warn_venv:
889 warn(
889 warn(
890 "Attempting to work in a virtualenv. If you encounter problems, "
890 "Attempting to work in a virtualenv. If you encounter problems, "
891 "please install IPython inside the virtualenv."
891 "please install IPython inside the virtualenv."
892 )
892 )
893 import site
893 import site
894 sys.path.insert(0, virtual_env)
894 sys.path.insert(0, virtual_env)
895 site.addsitedir(virtual_env)
895 site.addsitedir(virtual_env)
896
896
897 #-------------------------------------------------------------------------
897 #-------------------------------------------------------------------------
898 # Things related to injections into the sys module
898 # Things related to injections into the sys module
899 #-------------------------------------------------------------------------
899 #-------------------------------------------------------------------------
900
900
901 def save_sys_module_state(self):
901 def save_sys_module_state(self):
902 """Save the state of hooks in the sys module.
902 """Save the state of hooks in the sys module.
903
903
904 This has to be called after self.user_module is created.
904 This has to be called after self.user_module is created.
905 """
905 """
906 self._orig_sys_module_state = {'stdin': sys.stdin,
906 self._orig_sys_module_state = {'stdin': sys.stdin,
907 'stdout': sys.stdout,
907 'stdout': sys.stdout,
908 'stderr': sys.stderr,
908 'stderr': sys.stderr,
909 'excepthook': sys.excepthook}
909 'excepthook': sys.excepthook}
910 self._orig_sys_modules_main_name = self.user_module.__name__
910 self._orig_sys_modules_main_name = self.user_module.__name__
911 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
911 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
912
912
913 def restore_sys_module_state(self):
913 def restore_sys_module_state(self):
914 """Restore the state of the sys module."""
914 """Restore the state of the sys module."""
915 try:
915 try:
916 for k, v in self._orig_sys_module_state.items():
916 for k, v in self._orig_sys_module_state.items():
917 setattr(sys, k, v)
917 setattr(sys, k, v)
918 except AttributeError:
918 except AttributeError:
919 pass
919 pass
920 # Reset what what done in self.init_sys_modules
920 # Reset what what done in self.init_sys_modules
921 if self._orig_sys_modules_main_mod is not None:
921 if self._orig_sys_modules_main_mod is not None:
922 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
922 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
923
923
924 #-------------------------------------------------------------------------
924 #-------------------------------------------------------------------------
925 # Things related to the banner
925 # Things related to the banner
926 #-------------------------------------------------------------------------
926 #-------------------------------------------------------------------------
927
927
928 @property
928 @property
929 def banner(self):
929 def banner(self):
930 banner = self.banner1
930 banner = self.banner1
931 if self.profile and self.profile != 'default':
931 if self.profile and self.profile != 'default':
932 banner += '\nIPython profile: %s\n' % self.profile
932 banner += '\nIPython profile: %s\n' % self.profile
933 if self.banner2:
933 if self.banner2:
934 banner += '\n' + self.banner2
934 banner += '\n' + self.banner2
935 return banner
935 return banner
936
936
937 def show_banner(self, banner=None):
937 def show_banner(self, banner=None):
938 if banner is None:
938 if banner is None:
939 banner = self.banner
939 banner = self.banner
940 sys.stdout.write(banner)
940 sys.stdout.write(banner)
941
941
942 #-------------------------------------------------------------------------
942 #-------------------------------------------------------------------------
943 # Things related to hooks
943 # Things related to hooks
944 #-------------------------------------------------------------------------
944 #-------------------------------------------------------------------------
945
945
946 def init_hooks(self):
946 def init_hooks(self):
947 # hooks holds pointers used for user-side customizations
947 # hooks holds pointers used for user-side customizations
948 self.hooks = Struct()
948 self.hooks = Struct()
949
949
950 self.strdispatchers = {}
950 self.strdispatchers = {}
951
951
952 # Set all default hooks, defined in the IPython.hooks module.
952 # Set all default hooks, defined in the IPython.hooks module.
953 hooks = IPython.core.hooks
953 hooks = IPython.core.hooks
954 for hook_name in hooks.__all__:
954 for hook_name in hooks.__all__:
955 # default hooks have priority 100, i.e. low; user hooks should have
955 # default hooks have priority 100, i.e. low; user hooks should have
956 # 0-100 priority
956 # 0-100 priority
957 self.set_hook(hook_name, getattr(hooks, hook_name), 100)
957 self.set_hook(hook_name, getattr(hooks, hook_name), 100)
958
958
959 if self.display_page:
959 if self.display_page:
960 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
960 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
961
961
962 def set_hook(self, name, hook, priority=50, str_key=None, re_key=None):
962 def set_hook(self, name, hook, priority=50, str_key=None, re_key=None):
963 """set_hook(name,hook) -> sets an internal IPython hook.
963 """set_hook(name,hook) -> sets an internal IPython hook.
964
964
965 IPython exposes some of its internal API as user-modifiable hooks. By
965 IPython exposes some of its internal API as user-modifiable hooks. By
966 adding your function to one of these hooks, you can modify IPython's
966 adding your function to one of these hooks, you can modify IPython's
967 behavior to call at runtime your own routines."""
967 behavior to call at runtime your own routines."""
968
968
969 # At some point in the future, this should validate the hook before it
969 # At some point in the future, this should validate the hook before it
970 # accepts it. Probably at least check that the hook takes the number
970 # accepts it. Probably at least check that the hook takes the number
971 # of args it's supposed to.
971 # of args it's supposed to.
972
972
973 f = types.MethodType(hook,self)
973 f = types.MethodType(hook,self)
974
974
975 # check if the hook is for strdispatcher first
975 # check if the hook is for strdispatcher first
976 if str_key is not None:
976 if str_key is not None:
977 sdp = self.strdispatchers.get(name, StrDispatch())
977 sdp = self.strdispatchers.get(name, StrDispatch())
978 sdp.add_s(str_key, f, priority )
978 sdp.add_s(str_key, f, priority )
979 self.strdispatchers[name] = sdp
979 self.strdispatchers[name] = sdp
980 return
980 return
981 if re_key is not None:
981 if re_key is not None:
982 sdp = self.strdispatchers.get(name, StrDispatch())
982 sdp = self.strdispatchers.get(name, StrDispatch())
983 sdp.add_re(re.compile(re_key), f, priority )
983 sdp.add_re(re.compile(re_key), f, priority )
984 self.strdispatchers[name] = sdp
984 self.strdispatchers[name] = sdp
985 return
985 return
986
986
987 dp = getattr(self.hooks, name, None)
987 dp = getattr(self.hooks, name, None)
988 if name not in IPython.core.hooks.__all__:
988 if name not in IPython.core.hooks.__all__:
989 print("Warning! Hook '%s' is not one of %s" % \
989 print("Warning! Hook '%s' is not one of %s" % \
990 (name, IPython.core.hooks.__all__ ))
990 (name, IPython.core.hooks.__all__ ))
991
991
992 if name in IPython.core.hooks.deprecated:
992 if name in IPython.core.hooks.deprecated:
993 alternative = IPython.core.hooks.deprecated[name]
993 alternative = IPython.core.hooks.deprecated[name]
994 raise ValueError(
994 raise ValueError(
995 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
995 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
996 name, alternative
996 name, alternative
997 )
997 )
998 )
998 )
999
999
1000 if not dp:
1000 if not dp:
1001 dp = IPython.core.hooks.CommandChainDispatcher()
1001 dp = IPython.core.hooks.CommandChainDispatcher()
1002
1002
1003 try:
1003 try:
1004 dp.add(f,priority)
1004 dp.add(f,priority)
1005 except AttributeError:
1005 except AttributeError:
1006 # it was not commandchain, plain old func - replace
1006 # it was not commandchain, plain old func - replace
1007 dp = f
1007 dp = f
1008
1008
1009 setattr(self.hooks,name, dp)
1009 setattr(self.hooks,name, dp)
1010
1010
1011 #-------------------------------------------------------------------------
1011 #-------------------------------------------------------------------------
1012 # Things related to events
1012 # Things related to events
1013 #-------------------------------------------------------------------------
1013 #-------------------------------------------------------------------------
1014
1014
1015 def init_events(self):
1015 def init_events(self):
1016 self.events = EventManager(self, available_events)
1016 self.events = EventManager(self, available_events)
1017
1017
1018 self.events.register("pre_execute", self._clear_warning_registry)
1018 self.events.register("pre_execute", self._clear_warning_registry)
1019
1019
1020 def register_post_execute(self, func):
1020 def register_post_execute(self, func):
1021 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1021 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1022
1022
1023 Register a function for calling after code execution.
1023 Register a function for calling after code execution.
1024 """
1024 """
1025 raise ValueError(
1025 raise ValueError(
1026 "ip.register_post_execute is deprecated since IPython 1.0, use "
1026 "ip.register_post_execute is deprecated since IPython 1.0, use "
1027 "ip.events.register('post_run_cell', func) instead."
1027 "ip.events.register('post_run_cell', func) instead."
1028 )
1028 )
1029
1029
1030 def _clear_warning_registry(self):
1030 def _clear_warning_registry(self):
1031 # clear the warning registry, so that different code blocks with
1031 # clear the warning registry, so that different code blocks with
1032 # overlapping line number ranges don't cause spurious suppression of
1032 # overlapping line number ranges don't cause spurious suppression of
1033 # warnings (see gh-6611 for details)
1033 # warnings (see gh-6611 for details)
1034 if "__warningregistry__" in self.user_global_ns:
1034 if "__warningregistry__" in self.user_global_ns:
1035 del self.user_global_ns["__warningregistry__"]
1035 del self.user_global_ns["__warningregistry__"]
1036
1036
1037 #-------------------------------------------------------------------------
1037 #-------------------------------------------------------------------------
1038 # Things related to the "main" module
1038 # Things related to the "main" module
1039 #-------------------------------------------------------------------------
1039 #-------------------------------------------------------------------------
1040
1040
1041 def new_main_mod(self, filename, modname):
1041 def new_main_mod(self, filename, modname):
1042 """Return a new 'main' module object for user code execution.
1042 """Return a new 'main' module object for user code execution.
1043
1043
1044 ``filename`` should be the path of the script which will be run in the
1044 ``filename`` should be the path of the script which will be run in the
1045 module. Requests with the same filename will get the same module, with
1045 module. Requests with the same filename will get the same module, with
1046 its namespace cleared.
1046 its namespace cleared.
1047
1047
1048 ``modname`` should be the module name - normally either '__main__' or
1048 ``modname`` should be the module name - normally either '__main__' or
1049 the basename of the file without the extension.
1049 the basename of the file without the extension.
1050
1050
1051 When scripts are executed via %run, we must keep a reference to their
1051 When scripts are executed via %run, we must keep a reference to their
1052 __main__ module around so that Python doesn't
1052 __main__ module around so that Python doesn't
1053 clear it, rendering references to module globals useless.
1053 clear it, rendering references to module globals useless.
1054
1054
1055 This method keeps said reference in a private dict, keyed by the
1055 This method keeps said reference in a private dict, keyed by the
1056 absolute path of the script. This way, for multiple executions of the
1056 absolute path of the script. This way, for multiple executions of the
1057 same script we only keep one copy of the namespace (the last one),
1057 same script we only keep one copy of the namespace (the last one),
1058 thus preventing memory leaks from old references while allowing the
1058 thus preventing memory leaks from old references while allowing the
1059 objects from the last execution to be accessible.
1059 objects from the last execution to be accessible.
1060 """
1060 """
1061 filename = os.path.abspath(filename)
1061 filename = os.path.abspath(filename)
1062 try:
1062 try:
1063 main_mod = self._main_mod_cache[filename]
1063 main_mod = self._main_mod_cache[filename]
1064 except KeyError:
1064 except KeyError:
1065 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1065 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1066 modname,
1066 modname,
1067 doc="Module created for script run in IPython")
1067 doc="Module created for script run in IPython")
1068 else:
1068 else:
1069 main_mod.__dict__.clear()
1069 main_mod.__dict__.clear()
1070 main_mod.__name__ = modname
1070 main_mod.__name__ = modname
1071
1071
1072 main_mod.__file__ = filename
1072 main_mod.__file__ = filename
1073 # It seems pydoc (and perhaps others) needs any module instance to
1073 # It seems pydoc (and perhaps others) needs any module instance to
1074 # implement a __nonzero__ method
1074 # implement a __nonzero__ method
1075 main_mod.__nonzero__ = lambda : True
1075 main_mod.__nonzero__ = lambda : True
1076
1076
1077 return main_mod
1077 return main_mod
1078
1078
1079 def clear_main_mod_cache(self):
1079 def clear_main_mod_cache(self):
1080 """Clear the cache of main modules.
1080 """Clear the cache of main modules.
1081
1081
1082 Mainly for use by utilities like %reset.
1082 Mainly for use by utilities like %reset.
1083
1083
1084 Examples
1084 Examples
1085 --------
1085 --------
1086 In [15]: import IPython
1086 In [15]: import IPython
1087
1087
1088 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1088 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1089
1089
1090 In [17]: len(_ip._main_mod_cache) > 0
1090 In [17]: len(_ip._main_mod_cache) > 0
1091 Out[17]: True
1091 Out[17]: True
1092
1092
1093 In [18]: _ip.clear_main_mod_cache()
1093 In [18]: _ip.clear_main_mod_cache()
1094
1094
1095 In [19]: len(_ip._main_mod_cache) == 0
1095 In [19]: len(_ip._main_mod_cache) == 0
1096 Out[19]: True
1096 Out[19]: True
1097 """
1097 """
1098 self._main_mod_cache.clear()
1098 self._main_mod_cache.clear()
1099
1099
1100 #-------------------------------------------------------------------------
1100 #-------------------------------------------------------------------------
1101 # Things related to debugging
1101 # Things related to debugging
1102 #-------------------------------------------------------------------------
1102 #-------------------------------------------------------------------------
1103
1103
1104 def init_pdb(self):
1104 def init_pdb(self):
1105 # Set calling of pdb on exceptions
1105 # Set calling of pdb on exceptions
1106 # self.call_pdb is a property
1106 # self.call_pdb is a property
1107 self.call_pdb = self.pdb
1107 self.call_pdb = self.pdb
1108
1108
1109 def _get_call_pdb(self):
1109 def _get_call_pdb(self):
1110 return self._call_pdb
1110 return self._call_pdb
1111
1111
1112 def _set_call_pdb(self,val):
1112 def _set_call_pdb(self,val):
1113
1113
1114 if val not in (0,1,False,True):
1114 if val not in (0,1,False,True):
1115 raise ValueError('new call_pdb value must be boolean')
1115 raise ValueError('new call_pdb value must be boolean')
1116
1116
1117 # store value in instance
1117 # store value in instance
1118 self._call_pdb = val
1118 self._call_pdb = val
1119
1119
1120 # notify the actual exception handlers
1120 # notify the actual exception handlers
1121 self.InteractiveTB.call_pdb = val
1121 self.InteractiveTB.call_pdb = val
1122
1122
1123 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1123 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1124 'Control auto-activation of pdb at exceptions')
1124 'Control auto-activation of pdb at exceptions')
1125
1125
1126 def debugger(self,force=False):
1126 def debugger(self,force=False):
1127 """Call the pdb debugger.
1127 """Call the pdb debugger.
1128
1128
1129 Keywords:
1129 Keywords:
1130
1130
1131 - force(False): by default, this routine checks the instance call_pdb
1131 - force(False): by default, this routine checks the instance call_pdb
1132 flag and does not actually invoke the debugger if the flag is false.
1132 flag and does not actually invoke the debugger if the flag is false.
1133 The 'force' option forces the debugger to activate even if the flag
1133 The 'force' option forces the debugger to activate even if the flag
1134 is false.
1134 is false.
1135 """
1135 """
1136
1136
1137 if not (force or self.call_pdb):
1137 if not (force or self.call_pdb):
1138 return
1138 return
1139
1139
1140 if not hasattr(sys,'last_traceback'):
1140 if not hasattr(sys,'last_traceback'):
1141 error('No traceback has been produced, nothing to debug.')
1141 error('No traceback has been produced, nothing to debug.')
1142 return
1142 return
1143
1143
1144 self.InteractiveTB.debugger(force=True)
1144 self.InteractiveTB.debugger(force=True)
1145
1145
1146 #-------------------------------------------------------------------------
1146 #-------------------------------------------------------------------------
1147 # Things related to IPython's various namespaces
1147 # Things related to IPython's various namespaces
1148 #-------------------------------------------------------------------------
1148 #-------------------------------------------------------------------------
1149 default_user_namespaces = True
1149 default_user_namespaces = True
1150
1150
1151 def init_create_namespaces(self, user_module=None, user_ns=None):
1151 def init_create_namespaces(self, user_module=None, user_ns=None):
1152 # Create the namespace where the user will operate. user_ns is
1152 # Create the namespace where the user will operate. user_ns is
1153 # normally the only one used, and it is passed to the exec calls as
1153 # normally the only one used, and it is passed to the exec calls as
1154 # the locals argument. But we do carry a user_global_ns namespace
1154 # the locals argument. But we do carry a user_global_ns namespace
1155 # given as the exec 'globals' argument, This is useful in embedding
1155 # given as the exec 'globals' argument, This is useful in embedding
1156 # situations where the ipython shell opens in a context where the
1156 # situations where the ipython shell opens in a context where the
1157 # distinction between locals and globals is meaningful. For
1157 # distinction between locals and globals is meaningful. For
1158 # non-embedded contexts, it is just the same object as the user_ns dict.
1158 # non-embedded contexts, it is just the same object as the user_ns dict.
1159
1159
1160 # FIXME. For some strange reason, __builtins__ is showing up at user
1160 # FIXME. For some strange reason, __builtins__ is showing up at user
1161 # level as a dict instead of a module. This is a manual fix, but I
1161 # level as a dict instead of a module. This is a manual fix, but I
1162 # should really track down where the problem is coming from. Alex
1162 # should really track down where the problem is coming from. Alex
1163 # Schmolck reported this problem first.
1163 # Schmolck reported this problem first.
1164
1164
1165 # A useful post by Alex Martelli on this topic:
1165 # A useful post by Alex Martelli on this topic:
1166 # Re: inconsistent value from __builtins__
1166 # Re: inconsistent value from __builtins__
1167 # Von: Alex Martelli <aleaxit@yahoo.com>
1167 # Von: Alex Martelli <aleaxit@yahoo.com>
1168 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1168 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1169 # Gruppen: comp.lang.python
1169 # Gruppen: comp.lang.python
1170
1170
1171 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1171 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1172 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1172 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1173 # > <type 'dict'>
1173 # > <type 'dict'>
1174 # > >>> print type(__builtins__)
1174 # > >>> print type(__builtins__)
1175 # > <type 'module'>
1175 # > <type 'module'>
1176 # > Is this difference in return value intentional?
1176 # > Is this difference in return value intentional?
1177
1177
1178 # Well, it's documented that '__builtins__' can be either a dictionary
1178 # Well, it's documented that '__builtins__' can be either a dictionary
1179 # or a module, and it's been that way for a long time. Whether it's
1179 # or a module, and it's been that way for a long time. Whether it's
1180 # intentional (or sensible), I don't know. In any case, the idea is
1180 # intentional (or sensible), I don't know. In any case, the idea is
1181 # that if you need to access the built-in namespace directly, you
1181 # that if you need to access the built-in namespace directly, you
1182 # should start with "import __builtin__" (note, no 's') which will
1182 # should start with "import __builtin__" (note, no 's') which will
1183 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1183 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1184
1184
1185 # These routines return a properly built module and dict as needed by
1185 # These routines return a properly built module and dict as needed by
1186 # the rest of the code, and can also be used by extension writers to
1186 # the rest of the code, and can also be used by extension writers to
1187 # generate properly initialized namespaces.
1187 # generate properly initialized namespaces.
1188 if (user_ns is not None) or (user_module is not None):
1188 if (user_ns is not None) or (user_module is not None):
1189 self.default_user_namespaces = False
1189 self.default_user_namespaces = False
1190 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1190 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1191
1191
1192 # A record of hidden variables we have added to the user namespace, so
1192 # A record of hidden variables we have added to the user namespace, so
1193 # we can list later only variables defined in actual interactive use.
1193 # we can list later only variables defined in actual interactive use.
1194 self.user_ns_hidden = {}
1194 self.user_ns_hidden = {}
1195
1195
1196 # Now that FakeModule produces a real module, we've run into a nasty
1196 # Now that FakeModule produces a real module, we've run into a nasty
1197 # problem: after script execution (via %run), the module where the user
1197 # problem: after script execution (via %run), the module where the user
1198 # code ran is deleted. Now that this object is a true module (needed
1198 # code ran is deleted. Now that this object is a true module (needed
1199 # so doctest and other tools work correctly), the Python module
1199 # so doctest and other tools work correctly), the Python module
1200 # teardown mechanism runs over it, and sets to None every variable
1200 # teardown mechanism runs over it, and sets to None every variable
1201 # present in that module. Top-level references to objects from the
1201 # present in that module. Top-level references to objects from the
1202 # script survive, because the user_ns is updated with them. However,
1202 # script survive, because the user_ns is updated with them. However,
1203 # calling functions defined in the script that use other things from
1203 # calling functions defined in the script that use other things from
1204 # the script will fail, because the function's closure had references
1204 # the script will fail, because the function's closure had references
1205 # to the original objects, which are now all None. So we must protect
1205 # to the original objects, which are now all None. So we must protect
1206 # these modules from deletion by keeping a cache.
1206 # these modules from deletion by keeping a cache.
1207 #
1207 #
1208 # To avoid keeping stale modules around (we only need the one from the
1208 # To avoid keeping stale modules around (we only need the one from the
1209 # last run), we use a dict keyed with the full path to the script, so
1209 # last run), we use a dict keyed with the full path to the script, so
1210 # only the last version of the module is held in the cache. Note,
1210 # only the last version of the module is held in the cache. Note,
1211 # however, that we must cache the module *namespace contents* (their
1211 # however, that we must cache the module *namespace contents* (their
1212 # __dict__). Because if we try to cache the actual modules, old ones
1212 # __dict__). Because if we try to cache the actual modules, old ones
1213 # (uncached) could be destroyed while still holding references (such as
1213 # (uncached) could be destroyed while still holding references (such as
1214 # those held by GUI objects that tend to be long-lived)>
1214 # those held by GUI objects that tend to be long-lived)>
1215 #
1215 #
1216 # The %reset command will flush this cache. See the cache_main_mod()
1216 # The %reset command will flush this cache. See the cache_main_mod()
1217 # and clear_main_mod_cache() methods for details on use.
1217 # and clear_main_mod_cache() methods for details on use.
1218
1218
1219 # This is the cache used for 'main' namespaces
1219 # This is the cache used for 'main' namespaces
1220 self._main_mod_cache = {}
1220 self._main_mod_cache = {}
1221
1221
1222 # A table holding all the namespaces IPython deals with, so that
1222 # A table holding all the namespaces IPython deals with, so that
1223 # introspection facilities can search easily.
1223 # introspection facilities can search easily.
1224 self.ns_table = {'user_global':self.user_module.__dict__,
1224 self.ns_table = {'user_global':self.user_module.__dict__,
1225 'user_local':self.user_ns,
1225 'user_local':self.user_ns,
1226 'builtin':builtin_mod.__dict__
1226 'builtin':builtin_mod.__dict__
1227 }
1227 }
1228
1228
1229 @property
1229 @property
1230 def user_global_ns(self):
1230 def user_global_ns(self):
1231 return self.user_module.__dict__
1231 return self.user_module.__dict__
1232
1232
1233 def prepare_user_module(self, user_module=None, user_ns=None):
1233 def prepare_user_module(self, user_module=None, user_ns=None):
1234 """Prepare the module and namespace in which user code will be run.
1234 """Prepare the module and namespace in which user code will be run.
1235
1235
1236 When IPython is started normally, both parameters are None: a new module
1236 When IPython is started normally, both parameters are None: a new module
1237 is created automatically, and its __dict__ used as the namespace.
1237 is created automatically, and its __dict__ used as the namespace.
1238
1238
1239 If only user_module is provided, its __dict__ is used as the namespace.
1239 If only user_module is provided, its __dict__ is used as the namespace.
1240 If only user_ns is provided, a dummy module is created, and user_ns
1240 If only user_ns is provided, a dummy module is created, and user_ns
1241 becomes the global namespace. If both are provided (as they may be
1241 becomes the global namespace. If both are provided (as they may be
1242 when embedding), user_ns is the local namespace, and user_module
1242 when embedding), user_ns is the local namespace, and user_module
1243 provides the global namespace.
1243 provides the global namespace.
1244
1244
1245 Parameters
1245 Parameters
1246 ----------
1246 ----------
1247 user_module : module, optional
1247 user_module : module, optional
1248 The current user module in which IPython is being run. If None,
1248 The current user module in which IPython is being run. If None,
1249 a clean module will be created.
1249 a clean module will be created.
1250 user_ns : dict, optional
1250 user_ns : dict, optional
1251 A namespace in which to run interactive commands.
1251 A namespace in which to run interactive commands.
1252
1252
1253 Returns
1253 Returns
1254 -------
1254 -------
1255 A tuple of user_module and user_ns, each properly initialised.
1255 A tuple of user_module and user_ns, each properly initialised.
1256 """
1256 """
1257 if user_module is None and user_ns is not None:
1257 if user_module is None and user_ns is not None:
1258 user_ns.setdefault("__name__", "__main__")
1258 user_ns.setdefault("__name__", "__main__")
1259 user_module = DummyMod()
1259 user_module = DummyMod()
1260 user_module.__dict__ = user_ns
1260 user_module.__dict__ = user_ns
1261
1261
1262 if user_module is None:
1262 if user_module is None:
1263 user_module = types.ModuleType("__main__",
1263 user_module = types.ModuleType("__main__",
1264 doc="Automatically created module for IPython interactive environment")
1264 doc="Automatically created module for IPython interactive environment")
1265
1265
1266 # We must ensure that __builtin__ (without the final 's') is always
1266 # We must ensure that __builtin__ (without the final 's') is always
1267 # available and pointing to the __builtin__ *module*. For more details:
1267 # available and pointing to the __builtin__ *module*. For more details:
1268 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1268 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1269 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1269 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1270 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1270 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1271
1271
1272 if user_ns is None:
1272 if user_ns is None:
1273 user_ns = user_module.__dict__
1273 user_ns = user_module.__dict__
1274
1274
1275 return user_module, user_ns
1275 return user_module, user_ns
1276
1276
1277 def init_sys_modules(self):
1277 def init_sys_modules(self):
1278 # We need to insert into sys.modules something that looks like a
1278 # We need to insert into sys.modules something that looks like a
1279 # module but which accesses the IPython namespace, for shelve and
1279 # module but which accesses the IPython namespace, for shelve and
1280 # pickle to work interactively. Normally they rely on getting
1280 # pickle to work interactively. Normally they rely on getting
1281 # everything out of __main__, but for embedding purposes each IPython
1281 # everything out of __main__, but for embedding purposes each IPython
1282 # instance has its own private namespace, so we can't go shoving
1282 # instance has its own private namespace, so we can't go shoving
1283 # everything into __main__.
1283 # everything into __main__.
1284
1284
1285 # note, however, that we should only do this for non-embedded
1285 # note, however, that we should only do this for non-embedded
1286 # ipythons, which really mimic the __main__.__dict__ with their own
1286 # ipythons, which really mimic the __main__.__dict__ with their own
1287 # namespace. Embedded instances, on the other hand, should not do
1287 # namespace. Embedded instances, on the other hand, should not do
1288 # this because they need to manage the user local/global namespaces
1288 # this because they need to manage the user local/global namespaces
1289 # only, but they live within a 'normal' __main__ (meaning, they
1289 # only, but they live within a 'normal' __main__ (meaning, they
1290 # shouldn't overtake the execution environment of the script they're
1290 # shouldn't overtake the execution environment of the script they're
1291 # embedded in).
1291 # embedded in).
1292
1292
1293 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1293 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1294 main_name = self.user_module.__name__
1294 main_name = self.user_module.__name__
1295 sys.modules[main_name] = self.user_module
1295 sys.modules[main_name] = self.user_module
1296
1296
1297 def init_user_ns(self):
1297 def init_user_ns(self):
1298 """Initialize all user-visible namespaces to their minimum defaults.
1298 """Initialize all user-visible namespaces to their minimum defaults.
1299
1299
1300 Certain history lists are also initialized here, as they effectively
1300 Certain history lists are also initialized here, as they effectively
1301 act as user namespaces.
1301 act as user namespaces.
1302
1302
1303 Notes
1303 Notes
1304 -----
1304 -----
1305 All data structures here are only filled in, they are NOT reset by this
1305 All data structures here are only filled in, they are NOT reset by this
1306 method. If they were not empty before, data will simply be added to
1306 method. If they were not empty before, data will simply be added to
1307 them.
1307 them.
1308 """
1308 """
1309 # This function works in two parts: first we put a few things in
1309 # This function works in two parts: first we put a few things in
1310 # user_ns, and we sync that contents into user_ns_hidden so that these
1310 # user_ns, and we sync that contents into user_ns_hidden so that these
1311 # initial variables aren't shown by %who. After the sync, we add the
1311 # initial variables aren't shown by %who. After the sync, we add the
1312 # rest of what we *do* want the user to see with %who even on a new
1312 # rest of what we *do* want the user to see with %who even on a new
1313 # session (probably nothing, so they really only see their own stuff)
1313 # session (probably nothing, so they really only see their own stuff)
1314
1314
1315 # The user dict must *always* have a __builtin__ reference to the
1315 # The user dict must *always* have a __builtin__ reference to the
1316 # Python standard __builtin__ namespace, which must be imported.
1316 # Python standard __builtin__ namespace, which must be imported.
1317 # This is so that certain operations in prompt evaluation can be
1317 # This is so that certain operations in prompt evaluation can be
1318 # reliably executed with builtins. Note that we can NOT use
1318 # reliably executed with builtins. Note that we can NOT use
1319 # __builtins__ (note the 's'), because that can either be a dict or a
1319 # __builtins__ (note the 's'), because that can either be a dict or a
1320 # module, and can even mutate at runtime, depending on the context
1320 # module, and can even mutate at runtime, depending on the context
1321 # (Python makes no guarantees on it). In contrast, __builtin__ is
1321 # (Python makes no guarantees on it). In contrast, __builtin__ is
1322 # always a module object, though it must be explicitly imported.
1322 # always a module object, though it must be explicitly imported.
1323
1323
1324 # For more details:
1324 # For more details:
1325 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1325 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1326 ns = {}
1326 ns = {}
1327
1327
1328 # make global variables for user access to the histories
1328 # make global variables for user access to the histories
1329 ns['_ih'] = self.history_manager.input_hist_parsed
1329 ns['_ih'] = self.history_manager.input_hist_parsed
1330 ns['_oh'] = self.history_manager.output_hist
1330 ns['_oh'] = self.history_manager.output_hist
1331 ns['_dh'] = self.history_manager.dir_hist
1331 ns['_dh'] = self.history_manager.dir_hist
1332
1332
1333 # user aliases to input and output histories. These shouldn't show up
1333 # user aliases to input and output histories. These shouldn't show up
1334 # in %who, as they can have very large reprs.
1334 # in %who, as they can have very large reprs.
1335 ns['In'] = self.history_manager.input_hist_parsed
1335 ns['In'] = self.history_manager.input_hist_parsed
1336 ns['Out'] = self.history_manager.output_hist
1336 ns['Out'] = self.history_manager.output_hist
1337
1337
1338 # Store myself as the public api!!!
1338 # Store myself as the public api!!!
1339 ns['get_ipython'] = self.get_ipython
1339 ns['get_ipython'] = self.get_ipython
1340
1340
1341 ns['exit'] = self.exiter
1341 ns['exit'] = self.exiter
1342 ns['quit'] = self.exiter
1342 ns['quit'] = self.exiter
1343 ns["open"] = _modified_open
1343 ns["open"] = _modified_open
1344
1344
1345 # Sync what we've added so far to user_ns_hidden so these aren't seen
1345 # Sync what we've added so far to user_ns_hidden so these aren't seen
1346 # by %who
1346 # by %who
1347 self.user_ns_hidden.update(ns)
1347 self.user_ns_hidden.update(ns)
1348
1348
1349 # Anything put into ns now would show up in %who. Think twice before
1349 # Anything put into ns now would show up in %who. Think twice before
1350 # putting anything here, as we really want %who to show the user their
1350 # putting anything here, as we really want %who to show the user their
1351 # stuff, not our variables.
1351 # stuff, not our variables.
1352
1352
1353 # Finally, update the real user's namespace
1353 # Finally, update the real user's namespace
1354 self.user_ns.update(ns)
1354 self.user_ns.update(ns)
1355
1355
1356 @property
1356 @property
1357 def all_ns_refs(self):
1357 def all_ns_refs(self):
1358 """Get a list of references to all the namespace dictionaries in which
1358 """Get a list of references to all the namespace dictionaries in which
1359 IPython might store a user-created object.
1359 IPython might store a user-created object.
1360
1360
1361 Note that this does not include the displayhook, which also caches
1361 Note that this does not include the displayhook, which also caches
1362 objects from the output."""
1362 objects from the output."""
1363 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1363 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1364 [m.__dict__ for m in self._main_mod_cache.values()]
1364 [m.__dict__ for m in self._main_mod_cache.values()]
1365
1365
1366 def reset(self, new_session=True, aggressive=False):
1366 def reset(self, new_session=True, aggressive=False):
1367 """Clear all internal namespaces, and attempt to release references to
1367 """Clear all internal namespaces, and attempt to release references to
1368 user objects.
1368 user objects.
1369
1369
1370 If new_session is True, a new history session will be opened.
1370 If new_session is True, a new history session will be opened.
1371 """
1371 """
1372 # Clear histories
1372 # Clear histories
1373 self.history_manager.reset(new_session)
1373 self.history_manager.reset(new_session)
1374 # Reset counter used to index all histories
1374 # Reset counter used to index all histories
1375 if new_session:
1375 if new_session:
1376 self.execution_count = 1
1376 self.execution_count = 1
1377
1377
1378 # Reset last execution result
1378 # Reset last execution result
1379 self.last_execution_succeeded = True
1379 self.last_execution_succeeded = True
1380 self.last_execution_result = None
1380 self.last_execution_result = None
1381
1381
1382 # Flush cached output items
1382 # Flush cached output items
1383 if self.displayhook.do_full_cache:
1383 if self.displayhook.do_full_cache:
1384 self.displayhook.flush()
1384 self.displayhook.flush()
1385
1385
1386 # The main execution namespaces must be cleared very carefully,
1386 # The main execution namespaces must be cleared very carefully,
1387 # skipping the deletion of the builtin-related keys, because doing so
1387 # skipping the deletion of the builtin-related keys, because doing so
1388 # would cause errors in many object's __del__ methods.
1388 # would cause errors in many object's __del__ methods.
1389 if self.user_ns is not self.user_global_ns:
1389 if self.user_ns is not self.user_global_ns:
1390 self.user_ns.clear()
1390 self.user_ns.clear()
1391 ns = self.user_global_ns
1391 ns = self.user_global_ns
1392 drop_keys = set(ns.keys())
1392 drop_keys = set(ns.keys())
1393 drop_keys.discard('__builtin__')
1393 drop_keys.discard('__builtin__')
1394 drop_keys.discard('__builtins__')
1394 drop_keys.discard('__builtins__')
1395 drop_keys.discard('__name__')
1395 drop_keys.discard('__name__')
1396 for k in drop_keys:
1396 for k in drop_keys:
1397 del ns[k]
1397 del ns[k]
1398
1398
1399 self.user_ns_hidden.clear()
1399 self.user_ns_hidden.clear()
1400
1400
1401 # Restore the user namespaces to minimal usability
1401 # Restore the user namespaces to minimal usability
1402 self.init_user_ns()
1402 self.init_user_ns()
1403 if aggressive and not hasattr(self, "_sys_modules_keys"):
1403 if aggressive and not hasattr(self, "_sys_modules_keys"):
1404 print("Cannot restore sys.module, no snapshot")
1404 print("Cannot restore sys.module, no snapshot")
1405 elif aggressive:
1405 elif aggressive:
1406 print("culling sys module...")
1406 print("culling sys module...")
1407 current_keys = set(sys.modules.keys())
1407 current_keys = set(sys.modules.keys())
1408 for k in current_keys - self._sys_modules_keys:
1408 for k in current_keys - self._sys_modules_keys:
1409 if k.startswith("multiprocessing"):
1409 if k.startswith("multiprocessing"):
1410 continue
1410 continue
1411 del sys.modules[k]
1411 del sys.modules[k]
1412
1412
1413 # Restore the default and user aliases
1413 # Restore the default and user aliases
1414 self.alias_manager.clear_aliases()
1414 self.alias_manager.clear_aliases()
1415 self.alias_manager.init_aliases()
1415 self.alias_manager.init_aliases()
1416
1416
1417 # Now define aliases that only make sense on the terminal, because they
1417 # Now define aliases that only make sense on the terminal, because they
1418 # need direct access to the console in a way that we can't emulate in
1418 # need direct access to the console in a way that we can't emulate in
1419 # GUI or web frontend
1419 # GUI or web frontend
1420 if os.name == 'posix':
1420 if os.name == 'posix':
1421 for cmd in ('clear', 'more', 'less', 'man'):
1421 for cmd in ('clear', 'more', 'less', 'man'):
1422 if cmd not in self.magics_manager.magics['line']:
1422 if cmd not in self.magics_manager.magics['line']:
1423 self.alias_manager.soft_define_alias(cmd, cmd)
1423 self.alias_manager.soft_define_alias(cmd, cmd)
1424
1424
1425 # Flush the private list of module references kept for script
1425 # Flush the private list of module references kept for script
1426 # execution protection
1426 # execution protection
1427 self.clear_main_mod_cache()
1427 self.clear_main_mod_cache()
1428
1428
1429 def del_var(self, varname, by_name=False):
1429 def del_var(self, varname, by_name=False):
1430 """Delete a variable from the various namespaces, so that, as
1430 """Delete a variable from the various namespaces, so that, as
1431 far as possible, we're not keeping any hidden references to it.
1431 far as possible, we're not keeping any hidden references to it.
1432
1432
1433 Parameters
1433 Parameters
1434 ----------
1434 ----------
1435 varname : str
1435 varname : str
1436 The name of the variable to delete.
1436 The name of the variable to delete.
1437 by_name : bool
1437 by_name : bool
1438 If True, delete variables with the given name in each
1438 If True, delete variables with the given name in each
1439 namespace. If False (default), find the variable in the user
1439 namespace. If False (default), find the variable in the user
1440 namespace, and delete references to it.
1440 namespace, and delete references to it.
1441 """
1441 """
1442 if varname in ('__builtin__', '__builtins__'):
1442 if varname in ('__builtin__', '__builtins__'):
1443 raise ValueError("Refusing to delete %s" % varname)
1443 raise ValueError("Refusing to delete %s" % varname)
1444
1444
1445 ns_refs = self.all_ns_refs
1445 ns_refs = self.all_ns_refs
1446
1446
1447 if by_name: # Delete by name
1447 if by_name: # Delete by name
1448 for ns in ns_refs:
1448 for ns in ns_refs:
1449 try:
1449 try:
1450 del ns[varname]
1450 del ns[varname]
1451 except KeyError:
1451 except KeyError:
1452 pass
1452 pass
1453 else: # Delete by object
1453 else: # Delete by object
1454 try:
1454 try:
1455 obj = self.user_ns[varname]
1455 obj = self.user_ns[varname]
1456 except KeyError as e:
1456 except KeyError as e:
1457 raise NameError("name '%s' is not defined" % varname) from e
1457 raise NameError("name '%s' is not defined" % varname) from e
1458 # Also check in output history
1458 # Also check in output history
1459 ns_refs.append(self.history_manager.output_hist)
1459 ns_refs.append(self.history_manager.output_hist)
1460 for ns in ns_refs:
1460 for ns in ns_refs:
1461 to_delete = [n for n, o in ns.items() if o is obj]
1461 to_delete = [n for n, o in ns.items() if o is obj]
1462 for name in to_delete:
1462 for name in to_delete:
1463 del ns[name]
1463 del ns[name]
1464
1464
1465 # Ensure it is removed from the last execution result
1465 # Ensure it is removed from the last execution result
1466 if self.last_execution_result.result is obj:
1466 if self.last_execution_result.result is obj:
1467 self.last_execution_result = None
1467 self.last_execution_result = None
1468
1468
1469 # displayhook keeps extra references, but not in a dictionary
1469 # displayhook keeps extra references, but not in a dictionary
1470 for name in ('_', '__', '___'):
1470 for name in ('_', '__', '___'):
1471 if getattr(self.displayhook, name) is obj:
1471 if getattr(self.displayhook, name) is obj:
1472 setattr(self.displayhook, name, None)
1472 setattr(self.displayhook, name, None)
1473
1473
1474 def reset_selective(self, regex=None):
1474 def reset_selective(self, regex=None):
1475 """Clear selective variables from internal namespaces based on a
1475 """Clear selective variables from internal namespaces based on a
1476 specified regular expression.
1476 specified regular expression.
1477
1477
1478 Parameters
1478 Parameters
1479 ----------
1479 ----------
1480 regex : string or compiled pattern, optional
1480 regex : string or compiled pattern, optional
1481 A regular expression pattern that will be used in searching
1481 A regular expression pattern that will be used in searching
1482 variable names in the users namespaces.
1482 variable names in the users namespaces.
1483 """
1483 """
1484 if regex is not None:
1484 if regex is not None:
1485 try:
1485 try:
1486 m = re.compile(regex)
1486 m = re.compile(regex)
1487 except TypeError as e:
1487 except TypeError as e:
1488 raise TypeError('regex must be a string or compiled pattern') from e
1488 raise TypeError('regex must be a string or compiled pattern') from e
1489 # Search for keys in each namespace that match the given regex
1489 # Search for keys in each namespace that match the given regex
1490 # If a match is found, delete the key/value pair.
1490 # If a match is found, delete the key/value pair.
1491 for ns in self.all_ns_refs:
1491 for ns in self.all_ns_refs:
1492 for var in ns:
1492 for var in ns:
1493 if m.search(var):
1493 if m.search(var):
1494 del ns[var]
1494 del ns[var]
1495
1495
1496 def push(self, variables, interactive=True):
1496 def push(self, variables, interactive=True):
1497 """Inject a group of variables into the IPython user namespace.
1497 """Inject a group of variables into the IPython user namespace.
1498
1498
1499 Parameters
1499 Parameters
1500 ----------
1500 ----------
1501 variables : dict, str or list/tuple of str
1501 variables : dict, str or list/tuple of str
1502 The variables to inject into the user's namespace. If a dict, a
1502 The variables to inject into the user's namespace. If a dict, a
1503 simple update is done. If a str, the string is assumed to have
1503 simple update is done. If a str, the string is assumed to have
1504 variable names separated by spaces. A list/tuple of str can also
1504 variable names separated by spaces. A list/tuple of str can also
1505 be used to give the variable names. If just the variable names are
1505 be used to give the variable names. If just the variable names are
1506 give (list/tuple/str) then the variable values looked up in the
1506 give (list/tuple/str) then the variable values looked up in the
1507 callers frame.
1507 callers frame.
1508 interactive : bool
1508 interactive : bool
1509 If True (default), the variables will be listed with the ``who``
1509 If True (default), the variables will be listed with the ``who``
1510 magic.
1510 magic.
1511 """
1511 """
1512 vdict = None
1512 vdict = None
1513
1513
1514 # We need a dict of name/value pairs to do namespace updates.
1514 # We need a dict of name/value pairs to do namespace updates.
1515 if isinstance(variables, dict):
1515 if isinstance(variables, dict):
1516 vdict = variables
1516 vdict = variables
1517 elif isinstance(variables, (str, list, tuple)):
1517 elif isinstance(variables, (str, list, tuple)):
1518 if isinstance(variables, str):
1518 if isinstance(variables, str):
1519 vlist = variables.split()
1519 vlist = variables.split()
1520 else:
1520 else:
1521 vlist = variables
1521 vlist = variables
1522 vdict = {}
1522 vdict = {}
1523 cf = sys._getframe(1)
1523 cf = sys._getframe(1)
1524 for name in vlist:
1524 for name in vlist:
1525 try:
1525 try:
1526 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1526 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1527 except:
1527 except:
1528 print('Could not get variable %s from %s' %
1528 print('Could not get variable %s from %s' %
1529 (name,cf.f_code.co_name))
1529 (name,cf.f_code.co_name))
1530 else:
1530 else:
1531 raise ValueError('variables must be a dict/str/list/tuple')
1531 raise ValueError('variables must be a dict/str/list/tuple')
1532
1532
1533 # Propagate variables to user namespace
1533 # Propagate variables to user namespace
1534 self.user_ns.update(vdict)
1534 self.user_ns.update(vdict)
1535
1535
1536 # And configure interactive visibility
1536 # And configure interactive visibility
1537 user_ns_hidden = self.user_ns_hidden
1537 user_ns_hidden = self.user_ns_hidden
1538 if interactive:
1538 if interactive:
1539 for name in vdict:
1539 for name in vdict:
1540 user_ns_hidden.pop(name, None)
1540 user_ns_hidden.pop(name, None)
1541 else:
1541 else:
1542 user_ns_hidden.update(vdict)
1542 user_ns_hidden.update(vdict)
1543
1543
1544 def drop_by_id(self, variables):
1544 def drop_by_id(self, variables):
1545 """Remove a dict of variables from the user namespace, if they are the
1545 """Remove a dict of variables from the user namespace, if they are the
1546 same as the values in the dictionary.
1546 same as the values in the dictionary.
1547
1547
1548 This is intended for use by extensions: variables that they've added can
1548 This is intended for use by extensions: variables that they've added can
1549 be taken back out if they are unloaded, without removing any that the
1549 be taken back out if they are unloaded, without removing any that the
1550 user has overwritten.
1550 user has overwritten.
1551
1551
1552 Parameters
1552 Parameters
1553 ----------
1553 ----------
1554 variables : dict
1554 variables : dict
1555 A dictionary mapping object names (as strings) to the objects.
1555 A dictionary mapping object names (as strings) to the objects.
1556 """
1556 """
1557 for name, obj in variables.items():
1557 for name, obj in variables.items():
1558 if name in self.user_ns and self.user_ns[name] is obj:
1558 if name in self.user_ns and self.user_ns[name] is obj:
1559 del self.user_ns[name]
1559 del self.user_ns[name]
1560 self.user_ns_hidden.pop(name, None)
1560 self.user_ns_hidden.pop(name, None)
1561
1561
1562 #-------------------------------------------------------------------------
1562 #-------------------------------------------------------------------------
1563 # Things related to object introspection
1563 # Things related to object introspection
1564 #-------------------------------------------------------------------------
1564 #-------------------------------------------------------------------------
1565 @staticmethod
1565 @staticmethod
1566 def _find_parts(oname: str) -> Tuple[bool, ListType[str]]:
1566 def _find_parts(oname: str) -> Tuple[bool, ListType[str]]:
1567 """
1567 """
1568 Given an object name, return a list of parts of this object name.
1568 Given an object name, return a list of parts of this object name.
1569
1569
1570 Basically split on docs when using attribute access,
1570 Basically split on docs when using attribute access,
1571 and extract the value when using square bracket.
1571 and extract the value when using square bracket.
1572
1572
1573
1573
1574 For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x
1574 For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x
1575
1575
1576
1576
1577 Returns
1577 Returns
1578 -------
1578 -------
1579 parts_ok: bool
1579 parts_ok: bool
1580 wether we were properly able to parse parts.
1580 wether we were properly able to parse parts.
1581 parts: list of str
1581 parts: list of str
1582 extracted parts
1582 extracted parts
1583
1583
1584
1584
1585
1585
1586 """
1586 """
1587 raw_parts = oname.split(".")
1587 raw_parts = oname.split(".")
1588 parts = []
1588 parts = []
1589 parts_ok = True
1589 parts_ok = True
1590 for p in raw_parts:
1590 for p in raw_parts:
1591 if p.endswith("]"):
1591 if p.endswith("]"):
1592 var, *indices = p.split("[")
1592 var, *indices = p.split("[")
1593 if not var.isidentifier():
1593 if not var.isidentifier():
1594 parts_ok = False
1594 parts_ok = False
1595 break
1595 break
1596 parts.append(var)
1596 parts.append(var)
1597 for ind in indices:
1597 for ind in indices:
1598 if ind[-1] != "]" and not is_integer_string(ind[:-1]):
1598 if ind[-1] != "]" and not is_integer_string(ind[:-1]):
1599 parts_ok = False
1599 parts_ok = False
1600 break
1600 break
1601 parts.append(ind[:-1])
1601 parts.append(ind[:-1])
1602 continue
1602 continue
1603
1603
1604 if not p.isidentifier():
1604 if not p.isidentifier():
1605 parts_ok = False
1605 parts_ok = False
1606 parts.append(p)
1606 parts.append(p)
1607
1607
1608 return parts_ok, parts
1608 return parts_ok, parts
1609
1609
1610 def _ofind(
1610 def _ofind(
1611 self, oname: str, namespaces: Optional[Sequence[Tuple[str, AnyType]]] = None
1611 self, oname: str, namespaces: Optional[Sequence[Tuple[str, AnyType]]] = None
1612 ):
1612 ) -> OInfo:
1613 """Find an object in the available namespaces.
1613 """Find an object in the available namespaces.
1614
1614
1615 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1615
1616 Returns
1617 -------
1618 OInfo with fields:
1619 - ismagic
1620 - isalias
1621 - found
1622 - obj
1623 - namespac
1624 - parent
1616
1625
1617 Has special code to detect magic functions.
1626 Has special code to detect magic functions.
1618 """
1627 """
1619 oname = oname.strip()
1628 oname = oname.strip()
1620 parts_ok, parts = self._find_parts(oname)
1629 parts_ok, parts = self._find_parts(oname)
1621
1630
1622 if (
1631 if (
1623 not oname.startswith(ESC_MAGIC)
1632 not oname.startswith(ESC_MAGIC)
1624 and not oname.startswith(ESC_MAGIC2)
1633 and not oname.startswith(ESC_MAGIC2)
1625 and not parts_ok
1634 and not parts_ok
1626 ):
1635 ):
1627 return OInfo(
1636 return OInfo(
1628 ismagic=False,
1637 ismagic=False,
1629 isalias=False,
1638 isalias=False,
1630 found=False,
1639 found=False,
1631 obj=None,
1640 obj=None,
1632 namespace=None,
1641 namespace=None,
1633 parent=None,
1642 parent=None,
1634 )
1643 )
1635
1644
1636 if namespaces is None:
1645 if namespaces is None:
1637 # Namespaces to search in:
1646 # Namespaces to search in:
1638 # Put them in a list. The order is important so that we
1647 # Put them in a list. The order is important so that we
1639 # find things in the same order that Python finds them.
1648 # find things in the same order that Python finds them.
1640 namespaces = [ ('Interactive', self.user_ns),
1649 namespaces = [ ('Interactive', self.user_ns),
1641 ('Interactive (global)', self.user_global_ns),
1650 ('Interactive (global)', self.user_global_ns),
1642 ('Python builtin', builtin_mod.__dict__),
1651 ('Python builtin', builtin_mod.__dict__),
1643 ]
1652 ]
1644
1653
1645 ismagic = False
1654 ismagic = False
1646 isalias = False
1655 isalias = False
1647 found = False
1656 found = False
1648 ospace = None
1657 ospace = None
1649 parent = None
1658 parent = None
1650 obj = None
1659 obj = None
1651
1660
1652
1661
1653 # Look for the given name by splitting it in parts. If the head is
1662 # Look for the given name by splitting it in parts. If the head is
1654 # found, then we look for all the remaining parts as members, and only
1663 # found, then we look for all the remaining parts as members, and only
1655 # declare success if we can find them all.
1664 # declare success if we can find them all.
1656 oname_parts = parts
1665 oname_parts = parts
1657 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1666 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1658 for nsname,ns in namespaces:
1667 for nsname,ns in namespaces:
1659 try:
1668 try:
1660 obj = ns[oname_head]
1669 obj = ns[oname_head]
1661 except KeyError:
1670 except KeyError:
1662 continue
1671 continue
1663 else:
1672 else:
1664 for idx, part in enumerate(oname_rest):
1673 for idx, part in enumerate(oname_rest):
1665 try:
1674 try:
1666 parent = obj
1675 parent = obj
1667 # The last part is looked up in a special way to avoid
1676 # The last part is looked up in a special way to avoid
1668 # descriptor invocation as it may raise or have side
1677 # descriptor invocation as it may raise or have side
1669 # effects.
1678 # effects.
1670 if idx == len(oname_rest) - 1:
1679 if idx == len(oname_rest) - 1:
1671 obj = self._getattr_property(obj, part)
1680 obj = self._getattr_property(obj, part)
1672 else:
1681 else:
1673 if is_integer_string(part):
1682 if is_integer_string(part):
1674 obj = obj[int(part)]
1683 obj = obj[int(part)]
1675 else:
1684 else:
1676 obj = getattr(obj, part)
1685 obj = getattr(obj, part)
1677 except:
1686 except:
1678 # Blanket except b/c some badly implemented objects
1687 # Blanket except b/c some badly implemented objects
1679 # allow __getattr__ to raise exceptions other than
1688 # allow __getattr__ to raise exceptions other than
1680 # AttributeError, which then crashes IPython.
1689 # AttributeError, which then crashes IPython.
1681 break
1690 break
1682 else:
1691 else:
1683 # If we finish the for loop (no break), we got all members
1692 # If we finish the for loop (no break), we got all members
1684 found = True
1693 found = True
1685 ospace = nsname
1694 ospace = nsname
1686 break # namespace loop
1695 break # namespace loop
1687
1696
1688 # Try to see if it's magic
1697 # Try to see if it's magic
1689 if not found:
1698 if not found:
1690 obj = None
1699 obj = None
1691 if oname.startswith(ESC_MAGIC2):
1700 if oname.startswith(ESC_MAGIC2):
1692 oname = oname.lstrip(ESC_MAGIC2)
1701 oname = oname.lstrip(ESC_MAGIC2)
1693 obj = self.find_cell_magic(oname)
1702 obj = self.find_cell_magic(oname)
1694 elif oname.startswith(ESC_MAGIC):
1703 elif oname.startswith(ESC_MAGIC):
1695 oname = oname.lstrip(ESC_MAGIC)
1704 oname = oname.lstrip(ESC_MAGIC)
1696 obj = self.find_line_magic(oname)
1705 obj = self.find_line_magic(oname)
1697 else:
1706 else:
1698 # search without prefix, so run? will find %run?
1707 # search without prefix, so run? will find %run?
1699 obj = self.find_line_magic(oname)
1708 obj = self.find_line_magic(oname)
1700 if obj is None:
1709 if obj is None:
1701 obj = self.find_cell_magic(oname)
1710 obj = self.find_cell_magic(oname)
1702 if obj is not None:
1711 if obj is not None:
1703 found = True
1712 found = True
1704 ospace = 'IPython internal'
1713 ospace = 'IPython internal'
1705 ismagic = True
1714 ismagic = True
1706 isalias = isinstance(obj, Alias)
1715 isalias = isinstance(obj, Alias)
1707
1716
1708 # Last try: special-case some literals like '', [], {}, etc:
1717 # Last try: special-case some literals like '', [], {}, etc:
1709 if not found and oname_head in ["''",'""','[]','{}','()']:
1718 if not found and oname_head in ["''",'""','[]','{}','()']:
1710 obj = eval(oname_head)
1719 obj = eval(oname_head)
1711 found = True
1720 found = True
1712 ospace = 'Interactive'
1721 ospace = 'Interactive'
1713
1722
1714 return OInfo(
1723 return OInfo(
1715 obj=obj,
1724 obj=obj,
1716 found=found,
1725 found=found,
1717 parent=parent,
1726 parent=parent,
1718 ismagic=ismagic,
1727 ismagic=ismagic,
1719 isalias=isalias,
1728 isalias=isalias,
1720 namespace=ospace,
1729 namespace=ospace,
1721 )
1730 )
1722
1731
1723 @staticmethod
1732 @staticmethod
1724 def _getattr_property(obj, attrname):
1733 def _getattr_property(obj, attrname):
1725 """Property-aware getattr to use in object finding.
1734 """Property-aware getattr to use in object finding.
1726
1735
1727 If attrname represents a property, return it unevaluated (in case it has
1736 If attrname represents a property, return it unevaluated (in case it has
1728 side effects or raises an error.
1737 side effects or raises an error.
1729
1738
1730 """
1739 """
1731 if not isinstance(obj, type):
1740 if not isinstance(obj, type):
1732 try:
1741 try:
1733 # `getattr(type(obj), attrname)` is not guaranteed to return
1742 # `getattr(type(obj), attrname)` is not guaranteed to return
1734 # `obj`, but does so for property:
1743 # `obj`, but does so for property:
1735 #
1744 #
1736 # property.__get__(self, None, cls) -> self
1745 # property.__get__(self, None, cls) -> self
1737 #
1746 #
1738 # The universal alternative is to traverse the mro manually
1747 # The universal alternative is to traverse the mro manually
1739 # searching for attrname in class dicts.
1748 # searching for attrname in class dicts.
1740 if is_integer_string(attrname):
1749 if is_integer_string(attrname):
1741 return obj[int(attrname)]
1750 return obj[int(attrname)]
1742 else:
1751 else:
1743 attr = getattr(type(obj), attrname)
1752 attr = getattr(type(obj), attrname)
1744 except AttributeError:
1753 except AttributeError:
1745 pass
1754 pass
1746 else:
1755 else:
1747 # This relies on the fact that data descriptors (with both
1756 # This relies on the fact that data descriptors (with both
1748 # __get__ & __set__ magic methods) take precedence over
1757 # __get__ & __set__ magic methods) take precedence over
1749 # instance-level attributes:
1758 # instance-level attributes:
1750 #
1759 #
1751 # class A(object):
1760 # class A(object):
1752 # @property
1761 # @property
1753 # def foobar(self): return 123
1762 # def foobar(self): return 123
1754 # a = A()
1763 # a = A()
1755 # a.__dict__['foobar'] = 345
1764 # a.__dict__['foobar'] = 345
1756 # a.foobar # == 123
1765 # a.foobar # == 123
1757 #
1766 #
1758 # So, a property may be returned right away.
1767 # So, a property may be returned right away.
1759 if isinstance(attr, property):
1768 if isinstance(attr, property):
1760 return attr
1769 return attr
1761
1770
1762 # Nothing helped, fall back.
1771 # Nothing helped, fall back.
1763 return getattr(obj, attrname)
1772 return getattr(obj, attrname)
1764
1773
1765 def _object_find(self, oname, namespaces=None) -> OInfo:
1774 def _object_find(self, oname, namespaces=None) -> OInfo:
1766 """Find an object and return a struct with info about it."""
1775 """Find an object and return a struct with info about it."""
1767 return self._ofind(oname, namespaces)
1776 return self._ofind(oname, namespaces)
1768
1777
1769 def _inspect(self, meth, oname, namespaces=None, **kw):
1778 def _inspect(self, meth, oname, namespaces=None, **kw):
1770 """Generic interface to the inspector system.
1779 """Generic interface to the inspector system.
1771
1780
1772 This function is meant to be called by pdef, pdoc & friends.
1781 This function is meant to be called by pdef, pdoc & friends.
1773 """
1782 """
1774 info = self._object_find(oname, namespaces)
1783 info: OInfo = self._object_find(oname, namespaces)
1775 docformat = (
1784 docformat = (
1776 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1785 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1777 )
1786 )
1778 if info.found:
1787 if info.found or hasattr(info.parent, oinspect.HOOK_NAME):
1779 pmethod = getattr(self.inspector, meth)
1788 pmethod = getattr(self.inspector, meth)
1780 # TODO: only apply format_screen to the plain/text repr of the mime
1789 # TODO: only apply format_screen to the plain/text repr of the mime
1781 # bundle.
1790 # bundle.
1782 formatter = format_screen if info.ismagic else docformat
1791 formatter = format_screen if info.ismagic else docformat
1783 if meth == 'pdoc':
1792 if meth == 'pdoc':
1784 pmethod(info.obj, oname, formatter)
1793 pmethod(info.obj, oname, formatter)
1785 elif meth == 'pinfo':
1794 elif meth == 'pinfo':
1786 pmethod(
1795 pmethod(
1787 info.obj,
1796 info.obj,
1788 oname,
1797 oname,
1789 formatter,
1798 formatter,
1790 info,
1799 info,
1791 enable_html_pager=self.enable_html_pager,
1800 enable_html_pager=self.enable_html_pager,
1792 **kw,
1801 **kw,
1793 )
1802 )
1794 else:
1803 else:
1795 pmethod(info.obj, oname)
1804 pmethod(info.obj, oname)
1796 else:
1805 else:
1797 print('Object `%s` not found.' % oname)
1806 print('Object `%s` not found.' % oname)
1798 return 'not found' # so callers can take other action
1807 return 'not found' # so callers can take other action
1799
1808
1800 def object_inspect(self, oname, detail_level=0):
1809 def object_inspect(self, oname, detail_level=0):
1801 """Get object info about oname"""
1810 """Get object info about oname"""
1802 with self.builtin_trap:
1811 with self.builtin_trap:
1803 info = self._object_find(oname)
1812 info = self._object_find(oname)
1804 if info.found:
1813 if info.found:
1805 return self.inspector.info(info.obj, oname, info=info,
1814 return self.inspector.info(info.obj, oname, info=info,
1806 detail_level=detail_level
1815 detail_level=detail_level
1807 )
1816 )
1808 else:
1817 else:
1809 return oinspect.object_info(name=oname, found=False)
1818 return oinspect.object_info(name=oname, found=False)
1810
1819
1811 def object_inspect_text(self, oname, detail_level=0):
1820 def object_inspect_text(self, oname, detail_level=0):
1812 """Get object info as formatted text"""
1821 """Get object info as formatted text"""
1813 return self.object_inspect_mime(oname, detail_level)['text/plain']
1822 return self.object_inspect_mime(oname, detail_level)['text/plain']
1814
1823
1815 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1824 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1816 """Get object info as a mimebundle of formatted representations.
1825 """Get object info as a mimebundle of formatted representations.
1817
1826
1818 A mimebundle is a dictionary, keyed by mime-type.
1827 A mimebundle is a dictionary, keyed by mime-type.
1819 It must always have the key `'text/plain'`.
1828 It must always have the key `'text/plain'`.
1820 """
1829 """
1821 with self.builtin_trap:
1830 with self.builtin_trap:
1822 info = self._object_find(oname)
1831 info = self._object_find(oname)
1823 if info.found:
1832 if info.found:
1824 docformat = (
1833 docformat = (
1825 sphinxify(self.object_inspect(oname))
1834 sphinxify(self.object_inspect(oname))
1826 if self.sphinxify_docstring
1835 if self.sphinxify_docstring
1827 else None
1836 else None
1828 )
1837 )
1829 return self.inspector._get_info(
1838 return self.inspector._get_info(
1830 info.obj,
1839 info.obj,
1831 oname,
1840 oname,
1832 info=info,
1841 info=info,
1833 detail_level=detail_level,
1842 detail_level=detail_level,
1834 formatter=docformat,
1843 formatter=docformat,
1835 omit_sections=omit_sections,
1844 omit_sections=omit_sections,
1836 )
1845 )
1837 else:
1846 else:
1838 raise KeyError(oname)
1847 raise KeyError(oname)
1839
1848
1840 #-------------------------------------------------------------------------
1849 #-------------------------------------------------------------------------
1841 # Things related to history management
1850 # Things related to history management
1842 #-------------------------------------------------------------------------
1851 #-------------------------------------------------------------------------
1843
1852
1844 def init_history(self):
1853 def init_history(self):
1845 """Sets up the command history, and starts regular autosaves."""
1854 """Sets up the command history, and starts regular autosaves."""
1846 self.history_manager = HistoryManager(shell=self, parent=self)
1855 self.history_manager = HistoryManager(shell=self, parent=self)
1847 self.configurables.append(self.history_manager)
1856 self.configurables.append(self.history_manager)
1848
1857
1849 #-------------------------------------------------------------------------
1858 #-------------------------------------------------------------------------
1850 # Things related to exception handling and tracebacks (not debugging)
1859 # Things related to exception handling and tracebacks (not debugging)
1851 #-------------------------------------------------------------------------
1860 #-------------------------------------------------------------------------
1852
1861
1853 debugger_cls = InterruptiblePdb
1862 debugger_cls = InterruptiblePdb
1854
1863
1855 def init_traceback_handlers(self, custom_exceptions):
1864 def init_traceback_handlers(self, custom_exceptions):
1856 # Syntax error handler.
1865 # Syntax error handler.
1857 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1866 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1858
1867
1859 # The interactive one is initialized with an offset, meaning we always
1868 # The interactive one is initialized with an offset, meaning we always
1860 # want to remove the topmost item in the traceback, which is our own
1869 # want to remove the topmost item in the traceback, which is our own
1861 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1870 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1862 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1871 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1863 color_scheme='NoColor',
1872 color_scheme='NoColor',
1864 tb_offset = 1,
1873 tb_offset = 1,
1865 debugger_cls=self.debugger_cls, parent=self)
1874 debugger_cls=self.debugger_cls, parent=self)
1866
1875
1867 # The instance will store a pointer to the system-wide exception hook,
1876 # The instance will store a pointer to the system-wide exception hook,
1868 # so that runtime code (such as magics) can access it. This is because
1877 # so that runtime code (such as magics) can access it. This is because
1869 # during the read-eval loop, it may get temporarily overwritten.
1878 # during the read-eval loop, it may get temporarily overwritten.
1870 self.sys_excepthook = sys.excepthook
1879 self.sys_excepthook = sys.excepthook
1871
1880
1872 # and add any custom exception handlers the user may have specified
1881 # and add any custom exception handlers the user may have specified
1873 self.set_custom_exc(*custom_exceptions)
1882 self.set_custom_exc(*custom_exceptions)
1874
1883
1875 # Set the exception mode
1884 # Set the exception mode
1876 self.InteractiveTB.set_mode(mode=self.xmode)
1885 self.InteractiveTB.set_mode(mode=self.xmode)
1877
1886
1878 def set_custom_exc(self, exc_tuple, handler):
1887 def set_custom_exc(self, exc_tuple, handler):
1879 """set_custom_exc(exc_tuple, handler)
1888 """set_custom_exc(exc_tuple, handler)
1880
1889
1881 Set a custom exception handler, which will be called if any of the
1890 Set a custom exception handler, which will be called if any of the
1882 exceptions in exc_tuple occur in the mainloop (specifically, in the
1891 exceptions in exc_tuple occur in the mainloop (specifically, in the
1883 run_code() method).
1892 run_code() method).
1884
1893
1885 Parameters
1894 Parameters
1886 ----------
1895 ----------
1887 exc_tuple : tuple of exception classes
1896 exc_tuple : tuple of exception classes
1888 A *tuple* of exception classes, for which to call the defined
1897 A *tuple* of exception classes, for which to call the defined
1889 handler. It is very important that you use a tuple, and NOT A
1898 handler. It is very important that you use a tuple, and NOT A
1890 LIST here, because of the way Python's except statement works. If
1899 LIST here, because of the way Python's except statement works. If
1891 you only want to trap a single exception, use a singleton tuple::
1900 you only want to trap a single exception, use a singleton tuple::
1892
1901
1893 exc_tuple == (MyCustomException,)
1902 exc_tuple == (MyCustomException,)
1894
1903
1895 handler : callable
1904 handler : callable
1896 handler must have the following signature::
1905 handler must have the following signature::
1897
1906
1898 def my_handler(self, etype, value, tb, tb_offset=None):
1907 def my_handler(self, etype, value, tb, tb_offset=None):
1899 ...
1908 ...
1900 return structured_traceback
1909 return structured_traceback
1901
1910
1902 Your handler must return a structured traceback (a list of strings),
1911 Your handler must return a structured traceback (a list of strings),
1903 or None.
1912 or None.
1904
1913
1905 This will be made into an instance method (via types.MethodType)
1914 This will be made into an instance method (via types.MethodType)
1906 of IPython itself, and it will be called if any of the exceptions
1915 of IPython itself, and it will be called if any of the exceptions
1907 listed in the exc_tuple are caught. If the handler is None, an
1916 listed in the exc_tuple are caught. If the handler is None, an
1908 internal basic one is used, which just prints basic info.
1917 internal basic one is used, which just prints basic info.
1909
1918
1910 To protect IPython from crashes, if your handler ever raises an
1919 To protect IPython from crashes, if your handler ever raises an
1911 exception or returns an invalid result, it will be immediately
1920 exception or returns an invalid result, it will be immediately
1912 disabled.
1921 disabled.
1913
1922
1914 Notes
1923 Notes
1915 -----
1924 -----
1916 WARNING: by putting in your own exception handler into IPython's main
1925 WARNING: by putting in your own exception handler into IPython's main
1917 execution loop, you run a very good chance of nasty crashes. This
1926 execution loop, you run a very good chance of nasty crashes. This
1918 facility should only be used if you really know what you are doing.
1927 facility should only be used if you really know what you are doing.
1919 """
1928 """
1920
1929
1921 if not isinstance(exc_tuple, tuple):
1930 if not isinstance(exc_tuple, tuple):
1922 raise TypeError("The custom exceptions must be given as a tuple.")
1931 raise TypeError("The custom exceptions must be given as a tuple.")
1923
1932
1924 def dummy_handler(self, etype, value, tb, tb_offset=None):
1933 def dummy_handler(self, etype, value, tb, tb_offset=None):
1925 print('*** Simple custom exception handler ***')
1934 print('*** Simple custom exception handler ***')
1926 print('Exception type :', etype)
1935 print('Exception type :', etype)
1927 print('Exception value:', value)
1936 print('Exception value:', value)
1928 print('Traceback :', tb)
1937 print('Traceback :', tb)
1929
1938
1930 def validate_stb(stb):
1939 def validate_stb(stb):
1931 """validate structured traceback return type
1940 """validate structured traceback return type
1932
1941
1933 return type of CustomTB *should* be a list of strings, but allow
1942 return type of CustomTB *should* be a list of strings, but allow
1934 single strings or None, which are harmless.
1943 single strings or None, which are harmless.
1935
1944
1936 This function will *always* return a list of strings,
1945 This function will *always* return a list of strings,
1937 and will raise a TypeError if stb is inappropriate.
1946 and will raise a TypeError if stb is inappropriate.
1938 """
1947 """
1939 msg = "CustomTB must return list of strings, not %r" % stb
1948 msg = "CustomTB must return list of strings, not %r" % stb
1940 if stb is None:
1949 if stb is None:
1941 return []
1950 return []
1942 elif isinstance(stb, str):
1951 elif isinstance(stb, str):
1943 return [stb]
1952 return [stb]
1944 elif not isinstance(stb, list):
1953 elif not isinstance(stb, list):
1945 raise TypeError(msg)
1954 raise TypeError(msg)
1946 # it's a list
1955 # it's a list
1947 for line in stb:
1956 for line in stb:
1948 # check every element
1957 # check every element
1949 if not isinstance(line, str):
1958 if not isinstance(line, str):
1950 raise TypeError(msg)
1959 raise TypeError(msg)
1951 return stb
1960 return stb
1952
1961
1953 if handler is None:
1962 if handler is None:
1954 wrapped = dummy_handler
1963 wrapped = dummy_handler
1955 else:
1964 else:
1956 def wrapped(self,etype,value,tb,tb_offset=None):
1965 def wrapped(self,etype,value,tb,tb_offset=None):
1957 """wrap CustomTB handler, to protect IPython from user code
1966 """wrap CustomTB handler, to protect IPython from user code
1958
1967
1959 This makes it harder (but not impossible) for custom exception
1968 This makes it harder (but not impossible) for custom exception
1960 handlers to crash IPython.
1969 handlers to crash IPython.
1961 """
1970 """
1962 try:
1971 try:
1963 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1972 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1964 return validate_stb(stb)
1973 return validate_stb(stb)
1965 except:
1974 except:
1966 # clear custom handler immediately
1975 # clear custom handler immediately
1967 self.set_custom_exc((), None)
1976 self.set_custom_exc((), None)
1968 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1977 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1969 # show the exception in handler first
1978 # show the exception in handler first
1970 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1979 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1971 print(self.InteractiveTB.stb2text(stb))
1980 print(self.InteractiveTB.stb2text(stb))
1972 print("The original exception:")
1981 print("The original exception:")
1973 stb = self.InteractiveTB.structured_traceback(
1982 stb = self.InteractiveTB.structured_traceback(
1974 (etype,value,tb), tb_offset=tb_offset
1983 (etype,value,tb), tb_offset=tb_offset
1975 )
1984 )
1976 return stb
1985 return stb
1977
1986
1978 self.CustomTB = types.MethodType(wrapped,self)
1987 self.CustomTB = types.MethodType(wrapped,self)
1979 self.custom_exceptions = exc_tuple
1988 self.custom_exceptions = exc_tuple
1980
1989
1981 def excepthook(self, etype, value, tb):
1990 def excepthook(self, etype, value, tb):
1982 """One more defense for GUI apps that call sys.excepthook.
1991 """One more defense for GUI apps that call sys.excepthook.
1983
1992
1984 GUI frameworks like wxPython trap exceptions and call
1993 GUI frameworks like wxPython trap exceptions and call
1985 sys.excepthook themselves. I guess this is a feature that
1994 sys.excepthook themselves. I guess this is a feature that
1986 enables them to keep running after exceptions that would
1995 enables them to keep running after exceptions that would
1987 otherwise kill their mainloop. This is a bother for IPython
1996 otherwise kill their mainloop. This is a bother for IPython
1988 which expects to catch all of the program exceptions with a try:
1997 which expects to catch all of the program exceptions with a try:
1989 except: statement.
1998 except: statement.
1990
1999
1991 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2000 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1992 any app directly invokes sys.excepthook, it will look to the user like
2001 any app directly invokes sys.excepthook, it will look to the user like
1993 IPython crashed. In order to work around this, we can disable the
2002 IPython crashed. In order to work around this, we can disable the
1994 CrashHandler and replace it with this excepthook instead, which prints a
2003 CrashHandler and replace it with this excepthook instead, which prints a
1995 regular traceback using our InteractiveTB. In this fashion, apps which
2004 regular traceback using our InteractiveTB. In this fashion, apps which
1996 call sys.excepthook will generate a regular-looking exception from
2005 call sys.excepthook will generate a regular-looking exception from
1997 IPython, and the CrashHandler will only be triggered by real IPython
2006 IPython, and the CrashHandler will only be triggered by real IPython
1998 crashes.
2007 crashes.
1999
2008
2000 This hook should be used sparingly, only in places which are not likely
2009 This hook should be used sparingly, only in places which are not likely
2001 to be true IPython errors.
2010 to be true IPython errors.
2002 """
2011 """
2003 self.showtraceback((etype, value, tb), tb_offset=0)
2012 self.showtraceback((etype, value, tb), tb_offset=0)
2004
2013
2005 def _get_exc_info(self, exc_tuple=None):
2014 def _get_exc_info(self, exc_tuple=None):
2006 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
2015 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
2007
2016
2008 Ensures sys.last_type,value,traceback hold the exc_info we found,
2017 Ensures sys.last_type,value,traceback hold the exc_info we found,
2009 from whichever source.
2018 from whichever source.
2010
2019
2011 raises ValueError if none of these contain any information
2020 raises ValueError if none of these contain any information
2012 """
2021 """
2013 if exc_tuple is None:
2022 if exc_tuple is None:
2014 etype, value, tb = sys.exc_info()
2023 etype, value, tb = sys.exc_info()
2015 else:
2024 else:
2016 etype, value, tb = exc_tuple
2025 etype, value, tb = exc_tuple
2017
2026
2018 if etype is None:
2027 if etype is None:
2019 if hasattr(sys, 'last_type'):
2028 if hasattr(sys, 'last_type'):
2020 etype, value, tb = sys.last_type, sys.last_value, \
2029 etype, value, tb = sys.last_type, sys.last_value, \
2021 sys.last_traceback
2030 sys.last_traceback
2022
2031
2023 if etype is None:
2032 if etype is None:
2024 raise ValueError("No exception to find")
2033 raise ValueError("No exception to find")
2025
2034
2026 # Now store the exception info in sys.last_type etc.
2035 # Now store the exception info in sys.last_type etc.
2027 # WARNING: these variables are somewhat deprecated and not
2036 # WARNING: these variables are somewhat deprecated and not
2028 # necessarily safe to use in a threaded environment, but tools
2037 # necessarily safe to use in a threaded environment, but tools
2029 # like pdb depend on their existence, so let's set them. If we
2038 # like pdb depend on their existence, so let's set them. If we
2030 # find problems in the field, we'll need to revisit their use.
2039 # find problems in the field, we'll need to revisit their use.
2031 sys.last_type = etype
2040 sys.last_type = etype
2032 sys.last_value = value
2041 sys.last_value = value
2033 sys.last_traceback = tb
2042 sys.last_traceback = tb
2034
2043
2035 return etype, value, tb
2044 return etype, value, tb
2036
2045
2037 def show_usage_error(self, exc):
2046 def show_usage_error(self, exc):
2038 """Show a short message for UsageErrors
2047 """Show a short message for UsageErrors
2039
2048
2040 These are special exceptions that shouldn't show a traceback.
2049 These are special exceptions that shouldn't show a traceback.
2041 """
2050 """
2042 print("UsageError: %s" % exc, file=sys.stderr)
2051 print("UsageError: %s" % exc, file=sys.stderr)
2043
2052
2044 def get_exception_only(self, exc_tuple=None):
2053 def get_exception_only(self, exc_tuple=None):
2045 """
2054 """
2046 Return as a string (ending with a newline) the exception that
2055 Return as a string (ending with a newline) the exception that
2047 just occurred, without any traceback.
2056 just occurred, without any traceback.
2048 """
2057 """
2049 etype, value, tb = self._get_exc_info(exc_tuple)
2058 etype, value, tb = self._get_exc_info(exc_tuple)
2050 msg = traceback.format_exception_only(etype, value)
2059 msg = traceback.format_exception_only(etype, value)
2051 return ''.join(msg)
2060 return ''.join(msg)
2052
2061
2053 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
2062 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
2054 exception_only=False, running_compiled_code=False):
2063 exception_only=False, running_compiled_code=False):
2055 """Display the exception that just occurred.
2064 """Display the exception that just occurred.
2056
2065
2057 If nothing is known about the exception, this is the method which
2066 If nothing is known about the exception, this is the method which
2058 should be used throughout the code for presenting user tracebacks,
2067 should be used throughout the code for presenting user tracebacks,
2059 rather than directly invoking the InteractiveTB object.
2068 rather than directly invoking the InteractiveTB object.
2060
2069
2061 A specific showsyntaxerror() also exists, but this method can take
2070 A specific showsyntaxerror() also exists, but this method can take
2062 care of calling it if needed, so unless you are explicitly catching a
2071 care of calling it if needed, so unless you are explicitly catching a
2063 SyntaxError exception, don't try to analyze the stack manually and
2072 SyntaxError exception, don't try to analyze the stack manually and
2064 simply call this method."""
2073 simply call this method."""
2065
2074
2066 try:
2075 try:
2067 try:
2076 try:
2068 etype, value, tb = self._get_exc_info(exc_tuple)
2077 etype, value, tb = self._get_exc_info(exc_tuple)
2069 except ValueError:
2078 except ValueError:
2070 print('No traceback available to show.', file=sys.stderr)
2079 print('No traceback available to show.', file=sys.stderr)
2071 return
2080 return
2072
2081
2073 if issubclass(etype, SyntaxError):
2082 if issubclass(etype, SyntaxError):
2074 # Though this won't be called by syntax errors in the input
2083 # Though this won't be called by syntax errors in the input
2075 # line, there may be SyntaxError cases with imported code.
2084 # line, there may be SyntaxError cases with imported code.
2076 self.showsyntaxerror(filename, running_compiled_code)
2085 self.showsyntaxerror(filename, running_compiled_code)
2077 elif etype is UsageError:
2086 elif etype is UsageError:
2078 self.show_usage_error(value)
2087 self.show_usage_error(value)
2079 else:
2088 else:
2080 if exception_only:
2089 if exception_only:
2081 stb = ['An exception has occurred, use %tb to see '
2090 stb = ['An exception has occurred, use %tb to see '
2082 'the full traceback.\n']
2091 'the full traceback.\n']
2083 stb.extend(self.InteractiveTB.get_exception_only(etype,
2092 stb.extend(self.InteractiveTB.get_exception_only(etype,
2084 value))
2093 value))
2085 else:
2094 else:
2086 try:
2095 try:
2087 # Exception classes can customise their traceback - we
2096 # Exception classes can customise their traceback - we
2088 # use this in IPython.parallel for exceptions occurring
2097 # use this in IPython.parallel for exceptions occurring
2089 # in the engines. This should return a list of strings.
2098 # in the engines. This should return a list of strings.
2090 if hasattr(value, "_render_traceback_"):
2099 if hasattr(value, "_render_traceback_"):
2091 stb = value._render_traceback_()
2100 stb = value._render_traceback_()
2092 else:
2101 else:
2093 stb = self.InteractiveTB.structured_traceback(
2102 stb = self.InteractiveTB.structured_traceback(
2094 etype, value, tb, tb_offset=tb_offset
2103 etype, value, tb, tb_offset=tb_offset
2095 )
2104 )
2096
2105
2097 except Exception:
2106 except Exception:
2098 print(
2107 print(
2099 "Unexpected exception formatting exception. Falling back to standard exception"
2108 "Unexpected exception formatting exception. Falling back to standard exception"
2100 )
2109 )
2101 traceback.print_exc()
2110 traceback.print_exc()
2102 return None
2111 return None
2103
2112
2104 self._showtraceback(etype, value, stb)
2113 self._showtraceback(etype, value, stb)
2105 if self.call_pdb:
2114 if self.call_pdb:
2106 # drop into debugger
2115 # drop into debugger
2107 self.debugger(force=True)
2116 self.debugger(force=True)
2108 return
2117 return
2109
2118
2110 # Actually show the traceback
2119 # Actually show the traceback
2111 self._showtraceback(etype, value, stb)
2120 self._showtraceback(etype, value, stb)
2112
2121
2113 except KeyboardInterrupt:
2122 except KeyboardInterrupt:
2114 print('\n' + self.get_exception_only(), file=sys.stderr)
2123 print('\n' + self.get_exception_only(), file=sys.stderr)
2115
2124
2116 def _showtraceback(self, etype, evalue, stb: str):
2125 def _showtraceback(self, etype, evalue, stb: str):
2117 """Actually show a traceback.
2126 """Actually show a traceback.
2118
2127
2119 Subclasses may override this method to put the traceback on a different
2128 Subclasses may override this method to put the traceback on a different
2120 place, like a side channel.
2129 place, like a side channel.
2121 """
2130 """
2122 val = self.InteractiveTB.stb2text(stb)
2131 val = self.InteractiveTB.stb2text(stb)
2123 try:
2132 try:
2124 print(val)
2133 print(val)
2125 except UnicodeEncodeError:
2134 except UnicodeEncodeError:
2126 print(val.encode("utf-8", "backslashreplace").decode())
2135 print(val.encode("utf-8", "backslashreplace").decode())
2127
2136
2128 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2137 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2129 """Display the syntax error that just occurred.
2138 """Display the syntax error that just occurred.
2130
2139
2131 This doesn't display a stack trace because there isn't one.
2140 This doesn't display a stack trace because there isn't one.
2132
2141
2133 If a filename is given, it is stuffed in the exception instead
2142 If a filename is given, it is stuffed in the exception instead
2134 of what was there before (because Python's parser always uses
2143 of what was there before (because Python's parser always uses
2135 "<string>" when reading from a string).
2144 "<string>" when reading from a string).
2136
2145
2137 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2146 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2138 longer stack trace will be displayed.
2147 longer stack trace will be displayed.
2139 """
2148 """
2140 etype, value, last_traceback = self._get_exc_info()
2149 etype, value, last_traceback = self._get_exc_info()
2141
2150
2142 if filename and issubclass(etype, SyntaxError):
2151 if filename and issubclass(etype, SyntaxError):
2143 try:
2152 try:
2144 value.filename = filename
2153 value.filename = filename
2145 except:
2154 except:
2146 # Not the format we expect; leave it alone
2155 # Not the format we expect; leave it alone
2147 pass
2156 pass
2148
2157
2149 # If the error occurred when executing compiled code, we should provide full stacktrace.
2158 # If the error occurred when executing compiled code, we should provide full stacktrace.
2150 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2159 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2151 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2160 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2152 self._showtraceback(etype, value, stb)
2161 self._showtraceback(etype, value, stb)
2153
2162
2154 # This is overridden in TerminalInteractiveShell to show a message about
2163 # This is overridden in TerminalInteractiveShell to show a message about
2155 # the %paste magic.
2164 # the %paste magic.
2156 def showindentationerror(self):
2165 def showindentationerror(self):
2157 """Called by _run_cell when there's an IndentationError in code entered
2166 """Called by _run_cell when there's an IndentationError in code entered
2158 at the prompt.
2167 at the prompt.
2159
2168
2160 This is overridden in TerminalInteractiveShell to show a message about
2169 This is overridden in TerminalInteractiveShell to show a message about
2161 the %paste magic."""
2170 the %paste magic."""
2162 self.showsyntaxerror()
2171 self.showsyntaxerror()
2163
2172
2164 @skip_doctest
2173 @skip_doctest
2165 def set_next_input(self, s, replace=False):
2174 def set_next_input(self, s, replace=False):
2166 """ Sets the 'default' input string for the next command line.
2175 """ Sets the 'default' input string for the next command line.
2167
2176
2168 Example::
2177 Example::
2169
2178
2170 In [1]: _ip.set_next_input("Hello Word")
2179 In [1]: _ip.set_next_input("Hello Word")
2171 In [2]: Hello Word_ # cursor is here
2180 In [2]: Hello Word_ # cursor is here
2172 """
2181 """
2173 self.rl_next_input = s
2182 self.rl_next_input = s
2174
2183
2175 def _indent_current_str(self):
2184 def _indent_current_str(self):
2176 """return the current level of indentation as a string"""
2185 """return the current level of indentation as a string"""
2177 return self.input_splitter.get_indent_spaces() * ' '
2186 return self.input_splitter.get_indent_spaces() * ' '
2178
2187
2179 #-------------------------------------------------------------------------
2188 #-------------------------------------------------------------------------
2180 # Things related to text completion
2189 # Things related to text completion
2181 #-------------------------------------------------------------------------
2190 #-------------------------------------------------------------------------
2182
2191
2183 def init_completer(self):
2192 def init_completer(self):
2184 """Initialize the completion machinery.
2193 """Initialize the completion machinery.
2185
2194
2186 This creates completion machinery that can be used by client code,
2195 This creates completion machinery that can be used by client code,
2187 either interactively in-process (typically triggered by the readline
2196 either interactively in-process (typically triggered by the readline
2188 library), programmatically (such as in test suites) or out-of-process
2197 library), programmatically (such as in test suites) or out-of-process
2189 (typically over the network by remote frontends).
2198 (typically over the network by remote frontends).
2190 """
2199 """
2191 from IPython.core.completer import IPCompleter
2200 from IPython.core.completer import IPCompleter
2192 from IPython.core.completerlib import (
2201 from IPython.core.completerlib import (
2193 cd_completer,
2202 cd_completer,
2194 magic_run_completer,
2203 magic_run_completer,
2195 module_completer,
2204 module_completer,
2196 reset_completer,
2205 reset_completer,
2197 )
2206 )
2198
2207
2199 self.Completer = IPCompleter(shell=self,
2208 self.Completer = IPCompleter(shell=self,
2200 namespace=self.user_ns,
2209 namespace=self.user_ns,
2201 global_namespace=self.user_global_ns,
2210 global_namespace=self.user_global_ns,
2202 parent=self,
2211 parent=self,
2203 )
2212 )
2204 self.configurables.append(self.Completer)
2213 self.configurables.append(self.Completer)
2205
2214
2206 # Add custom completers to the basic ones built into IPCompleter
2215 # Add custom completers to the basic ones built into IPCompleter
2207 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2216 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2208 self.strdispatchers['complete_command'] = sdisp
2217 self.strdispatchers['complete_command'] = sdisp
2209 self.Completer.custom_completers = sdisp
2218 self.Completer.custom_completers = sdisp
2210
2219
2211 self.set_hook('complete_command', module_completer, str_key = 'import')
2220 self.set_hook('complete_command', module_completer, str_key = 'import')
2212 self.set_hook('complete_command', module_completer, str_key = 'from')
2221 self.set_hook('complete_command', module_completer, str_key = 'from')
2213 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2222 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2214 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2223 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2215 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2224 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2216 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2225 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2217
2226
2218 @skip_doctest
2227 @skip_doctest
2219 def complete(self, text, line=None, cursor_pos=None):
2228 def complete(self, text, line=None, cursor_pos=None):
2220 """Return the completed text and a list of completions.
2229 """Return the completed text and a list of completions.
2221
2230
2222 Parameters
2231 Parameters
2223 ----------
2232 ----------
2224 text : string
2233 text : string
2225 A string of text to be completed on. It can be given as empty and
2234 A string of text to be completed on. It can be given as empty and
2226 instead a line/position pair are given. In this case, the
2235 instead a line/position pair are given. In this case, the
2227 completer itself will split the line like readline does.
2236 completer itself will split the line like readline does.
2228 line : string, optional
2237 line : string, optional
2229 The complete line that text is part of.
2238 The complete line that text is part of.
2230 cursor_pos : int, optional
2239 cursor_pos : int, optional
2231 The position of the cursor on the input line.
2240 The position of the cursor on the input line.
2232
2241
2233 Returns
2242 Returns
2234 -------
2243 -------
2235 text : string
2244 text : string
2236 The actual text that was completed.
2245 The actual text that was completed.
2237 matches : list
2246 matches : list
2238 A sorted list with all possible completions.
2247 A sorted list with all possible completions.
2239
2248
2240 Notes
2249 Notes
2241 -----
2250 -----
2242 The optional arguments allow the completion to take more context into
2251 The optional arguments allow the completion to take more context into
2243 account, and are part of the low-level completion API.
2252 account, and are part of the low-level completion API.
2244
2253
2245 This is a wrapper around the completion mechanism, similar to what
2254 This is a wrapper around the completion mechanism, similar to what
2246 readline does at the command line when the TAB key is hit. By
2255 readline does at the command line when the TAB key is hit. By
2247 exposing it as a method, it can be used by other non-readline
2256 exposing it as a method, it can be used by other non-readline
2248 environments (such as GUIs) for text completion.
2257 environments (such as GUIs) for text completion.
2249
2258
2250 Examples
2259 Examples
2251 --------
2260 --------
2252 In [1]: x = 'hello'
2261 In [1]: x = 'hello'
2253
2262
2254 In [2]: _ip.complete('x.l')
2263 In [2]: _ip.complete('x.l')
2255 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2264 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2256 """
2265 """
2257
2266
2258 # Inject names into __builtin__ so we can complete on the added names.
2267 # Inject names into __builtin__ so we can complete on the added names.
2259 with self.builtin_trap:
2268 with self.builtin_trap:
2260 return self.Completer.complete(text, line, cursor_pos)
2269 return self.Completer.complete(text, line, cursor_pos)
2261
2270
2262 def set_custom_completer(self, completer, pos=0) -> None:
2271 def set_custom_completer(self, completer, pos=0) -> None:
2263 """Adds a new custom completer function.
2272 """Adds a new custom completer function.
2264
2273
2265 The position argument (defaults to 0) is the index in the completers
2274 The position argument (defaults to 0) is the index in the completers
2266 list where you want the completer to be inserted.
2275 list where you want the completer to be inserted.
2267
2276
2268 `completer` should have the following signature::
2277 `completer` should have the following signature::
2269
2278
2270 def completion(self: Completer, text: string) -> List[str]:
2279 def completion(self: Completer, text: string) -> List[str]:
2271 raise NotImplementedError
2280 raise NotImplementedError
2272
2281
2273 It will be bound to the current Completer instance and pass some text
2282 It will be bound to the current Completer instance and pass some text
2274 and return a list with current completions to suggest to the user.
2283 and return a list with current completions to suggest to the user.
2275 """
2284 """
2276
2285
2277 newcomp = types.MethodType(completer, self.Completer)
2286 newcomp = types.MethodType(completer, self.Completer)
2278 self.Completer.custom_matchers.insert(pos,newcomp)
2287 self.Completer.custom_matchers.insert(pos,newcomp)
2279
2288
2280 def set_completer_frame(self, frame=None):
2289 def set_completer_frame(self, frame=None):
2281 """Set the frame of the completer."""
2290 """Set the frame of the completer."""
2282 if frame:
2291 if frame:
2283 self.Completer.namespace = frame.f_locals
2292 self.Completer.namespace = frame.f_locals
2284 self.Completer.global_namespace = frame.f_globals
2293 self.Completer.global_namespace = frame.f_globals
2285 else:
2294 else:
2286 self.Completer.namespace = self.user_ns
2295 self.Completer.namespace = self.user_ns
2287 self.Completer.global_namespace = self.user_global_ns
2296 self.Completer.global_namespace = self.user_global_ns
2288
2297
2289 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2290 # Things related to magics
2299 # Things related to magics
2291 #-------------------------------------------------------------------------
2300 #-------------------------------------------------------------------------
2292
2301
2293 def init_magics(self):
2302 def init_magics(self):
2294 from IPython.core import magics as m
2303 from IPython.core import magics as m
2295 self.magics_manager = magic.MagicsManager(shell=self,
2304 self.magics_manager = magic.MagicsManager(shell=self,
2296 parent=self,
2305 parent=self,
2297 user_magics=m.UserMagics(self))
2306 user_magics=m.UserMagics(self))
2298 self.configurables.append(self.magics_manager)
2307 self.configurables.append(self.magics_manager)
2299
2308
2300 # Expose as public API from the magics manager
2309 # Expose as public API from the magics manager
2301 self.register_magics = self.magics_manager.register
2310 self.register_magics = self.magics_manager.register
2302
2311
2303 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2312 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2304 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2313 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2305 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2314 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2306 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2315 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2307 m.PylabMagics, m.ScriptMagics,
2316 m.PylabMagics, m.ScriptMagics,
2308 )
2317 )
2309 self.register_magics(m.AsyncMagics)
2318 self.register_magics(m.AsyncMagics)
2310
2319
2311 # Register Magic Aliases
2320 # Register Magic Aliases
2312 mman = self.magics_manager
2321 mman = self.magics_manager
2313 # FIXME: magic aliases should be defined by the Magics classes
2322 # FIXME: magic aliases should be defined by the Magics classes
2314 # or in MagicsManager, not here
2323 # or in MagicsManager, not here
2315 mman.register_alias('ed', 'edit')
2324 mman.register_alias('ed', 'edit')
2316 mman.register_alias('hist', 'history')
2325 mman.register_alias('hist', 'history')
2317 mman.register_alias('rep', 'recall')
2326 mman.register_alias('rep', 'recall')
2318 mman.register_alias('SVG', 'svg', 'cell')
2327 mman.register_alias('SVG', 'svg', 'cell')
2319 mman.register_alias('HTML', 'html', 'cell')
2328 mman.register_alias('HTML', 'html', 'cell')
2320 mman.register_alias('file', 'writefile', 'cell')
2329 mman.register_alias('file', 'writefile', 'cell')
2321
2330
2322 # FIXME: Move the color initialization to the DisplayHook, which
2331 # FIXME: Move the color initialization to the DisplayHook, which
2323 # should be split into a prompt manager and displayhook. We probably
2332 # should be split into a prompt manager and displayhook. We probably
2324 # even need a centralize colors management object.
2333 # even need a centralize colors management object.
2325 self.run_line_magic('colors', self.colors)
2334 self.run_line_magic('colors', self.colors)
2326
2335
2327 # Defined here so that it's included in the documentation
2336 # Defined here so that it's included in the documentation
2328 @functools.wraps(magic.MagicsManager.register_function)
2337 @functools.wraps(magic.MagicsManager.register_function)
2329 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2338 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2330 self.magics_manager.register_function(
2339 self.magics_manager.register_function(
2331 func, magic_kind=magic_kind, magic_name=magic_name
2340 func, magic_kind=magic_kind, magic_name=magic_name
2332 )
2341 )
2333
2342
2334 def _find_with_lazy_load(self, /, type_, magic_name: str):
2343 def _find_with_lazy_load(self, /, type_, magic_name: str):
2335 """
2344 """
2336 Try to find a magic potentially lazy-loading it.
2345 Try to find a magic potentially lazy-loading it.
2337
2346
2338 Parameters
2347 Parameters
2339 ----------
2348 ----------
2340
2349
2341 type_: "line"|"cell"
2350 type_: "line"|"cell"
2342 the type of magics we are trying to find/lazy load.
2351 the type of magics we are trying to find/lazy load.
2343 magic_name: str
2352 magic_name: str
2344 The name of the magic we are trying to find/lazy load
2353 The name of the magic we are trying to find/lazy load
2345
2354
2346
2355
2347 Note that this may have any side effects
2356 Note that this may have any side effects
2348 """
2357 """
2349 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2358 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2350 fn = finder(magic_name)
2359 fn = finder(magic_name)
2351 if fn is not None:
2360 if fn is not None:
2352 return fn
2361 return fn
2353 lazy = self.magics_manager.lazy_magics.get(magic_name)
2362 lazy = self.magics_manager.lazy_magics.get(magic_name)
2354 if lazy is None:
2363 if lazy is None:
2355 return None
2364 return None
2356
2365
2357 self.run_line_magic("load_ext", lazy)
2366 self.run_line_magic("load_ext", lazy)
2358 res = finder(magic_name)
2367 res = finder(magic_name)
2359 return res
2368 return res
2360
2369
2361 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2370 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2362 """Execute the given line magic.
2371 """Execute the given line magic.
2363
2372
2364 Parameters
2373 Parameters
2365 ----------
2374 ----------
2366 magic_name : str
2375 magic_name : str
2367 Name of the desired magic function, without '%' prefix.
2376 Name of the desired magic function, without '%' prefix.
2368 line : str
2377 line : str
2369 The rest of the input line as a single string.
2378 The rest of the input line as a single string.
2370 _stack_depth : int
2379 _stack_depth : int
2371 If run_line_magic() is called from magic() then _stack_depth=2.
2380 If run_line_magic() is called from magic() then _stack_depth=2.
2372 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2381 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2373 """
2382 """
2374 fn = self._find_with_lazy_load("line", magic_name)
2383 fn = self._find_with_lazy_load("line", magic_name)
2375 if fn is None:
2384 if fn is None:
2376 lazy = self.magics_manager.lazy_magics.get(magic_name)
2385 lazy = self.magics_manager.lazy_magics.get(magic_name)
2377 if lazy:
2386 if lazy:
2378 self.run_line_magic("load_ext", lazy)
2387 self.run_line_magic("load_ext", lazy)
2379 fn = self.find_line_magic(magic_name)
2388 fn = self.find_line_magic(magic_name)
2380 if fn is None:
2389 if fn is None:
2381 cm = self.find_cell_magic(magic_name)
2390 cm = self.find_cell_magic(magic_name)
2382 etpl = "Line magic function `%%%s` not found%s."
2391 etpl = "Line magic function `%%%s` not found%s."
2383 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2392 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2384 'did you mean that instead?)' % magic_name )
2393 'did you mean that instead?)' % magic_name )
2385 raise UsageError(etpl % (magic_name, extra))
2394 raise UsageError(etpl % (magic_name, extra))
2386 else:
2395 else:
2387 # Note: this is the distance in the stack to the user's frame.
2396 # Note: this is the distance in the stack to the user's frame.
2388 # This will need to be updated if the internal calling logic gets
2397 # This will need to be updated if the internal calling logic gets
2389 # refactored, or else we'll be expanding the wrong variables.
2398 # refactored, or else we'll be expanding the wrong variables.
2390
2399
2391 # Determine stack_depth depending on where run_line_magic() has been called
2400 # Determine stack_depth depending on where run_line_magic() has been called
2392 stack_depth = _stack_depth
2401 stack_depth = _stack_depth
2393 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2402 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2394 # magic has opted out of var_expand
2403 # magic has opted out of var_expand
2395 magic_arg_s = line
2404 magic_arg_s = line
2396 else:
2405 else:
2397 magic_arg_s = self.var_expand(line, stack_depth)
2406 magic_arg_s = self.var_expand(line, stack_depth)
2398 # Put magic args in a list so we can call with f(*a) syntax
2407 # Put magic args in a list so we can call with f(*a) syntax
2399 args = [magic_arg_s]
2408 args = [magic_arg_s]
2400 kwargs = {}
2409 kwargs = {}
2401 # Grab local namespace if we need it:
2410 # Grab local namespace if we need it:
2402 if getattr(fn, "needs_local_scope", False):
2411 if getattr(fn, "needs_local_scope", False):
2403 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2412 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2404 with self.builtin_trap:
2413 with self.builtin_trap:
2405 result = fn(*args, **kwargs)
2414 result = fn(*args, **kwargs)
2406
2415
2407 # The code below prevents the output from being displayed
2416 # The code below prevents the output from being displayed
2408 # when using magics with decodator @output_can_be_silenced
2417 # when using magics with decodator @output_can_be_silenced
2409 # when the last Python token in the expression is a ';'.
2418 # when the last Python token in the expression is a ';'.
2410 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
2419 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
2411 if DisplayHook.semicolon_at_end_of_expression(magic_arg_s):
2420 if DisplayHook.semicolon_at_end_of_expression(magic_arg_s):
2412 return None
2421 return None
2413
2422
2414 return result
2423 return result
2415
2424
2416 def get_local_scope(self, stack_depth):
2425 def get_local_scope(self, stack_depth):
2417 """Get local scope at given stack depth.
2426 """Get local scope at given stack depth.
2418
2427
2419 Parameters
2428 Parameters
2420 ----------
2429 ----------
2421 stack_depth : int
2430 stack_depth : int
2422 Depth relative to calling frame
2431 Depth relative to calling frame
2423 """
2432 """
2424 return sys._getframe(stack_depth + 1).f_locals
2433 return sys._getframe(stack_depth + 1).f_locals
2425
2434
2426 def run_cell_magic(self, magic_name, line, cell):
2435 def run_cell_magic(self, magic_name, line, cell):
2427 """Execute the given cell magic.
2436 """Execute the given cell magic.
2428
2437
2429 Parameters
2438 Parameters
2430 ----------
2439 ----------
2431 magic_name : str
2440 magic_name : str
2432 Name of the desired magic function, without '%' prefix.
2441 Name of the desired magic function, without '%' prefix.
2433 line : str
2442 line : str
2434 The rest of the first input line as a single string.
2443 The rest of the first input line as a single string.
2435 cell : str
2444 cell : str
2436 The body of the cell as a (possibly multiline) string.
2445 The body of the cell as a (possibly multiline) string.
2437 """
2446 """
2438 fn = self._find_with_lazy_load("cell", magic_name)
2447 fn = self._find_with_lazy_load("cell", magic_name)
2439 if fn is None:
2448 if fn is None:
2440 lm = self.find_line_magic(magic_name)
2449 lm = self.find_line_magic(magic_name)
2441 etpl = "Cell magic `%%{0}` not found{1}."
2450 etpl = "Cell magic `%%{0}` not found{1}."
2442 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2451 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2443 'did you mean that instead?)'.format(magic_name))
2452 'did you mean that instead?)'.format(magic_name))
2444 raise UsageError(etpl.format(magic_name, extra))
2453 raise UsageError(etpl.format(magic_name, extra))
2445 elif cell == '':
2454 elif cell == '':
2446 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2455 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2447 if self.find_line_magic(magic_name) is not None:
2456 if self.find_line_magic(magic_name) is not None:
2448 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2457 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2449 raise UsageError(message)
2458 raise UsageError(message)
2450 else:
2459 else:
2451 # Note: this is the distance in the stack to the user's frame.
2460 # Note: this is the distance in the stack to the user's frame.
2452 # This will need to be updated if the internal calling logic gets
2461 # This will need to be updated if the internal calling logic gets
2453 # refactored, or else we'll be expanding the wrong variables.
2462 # refactored, or else we'll be expanding the wrong variables.
2454 stack_depth = 2
2463 stack_depth = 2
2455 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2464 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2456 # magic has opted out of var_expand
2465 # magic has opted out of var_expand
2457 magic_arg_s = line
2466 magic_arg_s = line
2458 else:
2467 else:
2459 magic_arg_s = self.var_expand(line, stack_depth)
2468 magic_arg_s = self.var_expand(line, stack_depth)
2460 kwargs = {}
2469 kwargs = {}
2461 if getattr(fn, "needs_local_scope", False):
2470 if getattr(fn, "needs_local_scope", False):
2462 kwargs['local_ns'] = self.user_ns
2471 kwargs['local_ns'] = self.user_ns
2463
2472
2464 with self.builtin_trap:
2473 with self.builtin_trap:
2465 args = (magic_arg_s, cell)
2474 args = (magic_arg_s, cell)
2466 result = fn(*args, **kwargs)
2475 result = fn(*args, **kwargs)
2467
2476
2468 # The code below prevents the output from being displayed
2477 # The code below prevents the output from being displayed
2469 # when using magics with decodator @output_can_be_silenced
2478 # when using magics with decodator @output_can_be_silenced
2470 # when the last Python token in the expression is a ';'.
2479 # when the last Python token in the expression is a ';'.
2471 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
2480 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
2472 if DisplayHook.semicolon_at_end_of_expression(cell):
2481 if DisplayHook.semicolon_at_end_of_expression(cell):
2473 return None
2482 return None
2474
2483
2475 return result
2484 return result
2476
2485
2477 def find_line_magic(self, magic_name):
2486 def find_line_magic(self, magic_name):
2478 """Find and return a line magic by name.
2487 """Find and return a line magic by name.
2479
2488
2480 Returns None if the magic isn't found."""
2489 Returns None if the magic isn't found."""
2481 return self.magics_manager.magics['line'].get(magic_name)
2490 return self.magics_manager.magics['line'].get(magic_name)
2482
2491
2483 def find_cell_magic(self, magic_name):
2492 def find_cell_magic(self, magic_name):
2484 """Find and return a cell magic by name.
2493 """Find and return a cell magic by name.
2485
2494
2486 Returns None if the magic isn't found."""
2495 Returns None if the magic isn't found."""
2487 return self.magics_manager.magics['cell'].get(magic_name)
2496 return self.magics_manager.magics['cell'].get(magic_name)
2488
2497
2489 def find_magic(self, magic_name, magic_kind='line'):
2498 def find_magic(self, magic_name, magic_kind='line'):
2490 """Find and return a magic of the given type by name.
2499 """Find and return a magic of the given type by name.
2491
2500
2492 Returns None if the magic isn't found."""
2501 Returns None if the magic isn't found."""
2493 return self.magics_manager.magics[magic_kind].get(magic_name)
2502 return self.magics_manager.magics[magic_kind].get(magic_name)
2494
2503
2495 def magic(self, arg_s):
2504 def magic(self, arg_s):
2496 """
2505 """
2497 DEPRECATED
2506 DEPRECATED
2498
2507
2499 Deprecated since IPython 0.13 (warning added in
2508 Deprecated since IPython 0.13 (warning added in
2500 8.1), use run_line_magic(magic_name, parameter_s).
2509 8.1), use run_line_magic(magic_name, parameter_s).
2501
2510
2502 Call a magic function by name.
2511 Call a magic function by name.
2503
2512
2504 Input: a string containing the name of the magic function to call and
2513 Input: a string containing the name of the magic function to call and
2505 any additional arguments to be passed to the magic.
2514 any additional arguments to be passed to the magic.
2506
2515
2507 magic('name -opt foo bar') is equivalent to typing at the ipython
2516 magic('name -opt foo bar') is equivalent to typing at the ipython
2508 prompt:
2517 prompt:
2509
2518
2510 In[1]: %name -opt foo bar
2519 In[1]: %name -opt foo bar
2511
2520
2512 To call a magic without arguments, simply use magic('name').
2521 To call a magic without arguments, simply use magic('name').
2513
2522
2514 This provides a proper Python function to call IPython's magics in any
2523 This provides a proper Python function to call IPython's magics in any
2515 valid Python code you can type at the interpreter, including loops and
2524 valid Python code you can type at the interpreter, including loops and
2516 compound statements.
2525 compound statements.
2517 """
2526 """
2518 warnings.warn(
2527 warnings.warn(
2519 "`magic(...)` is deprecated since IPython 0.13 (warning added in "
2528 "`magic(...)` is deprecated since IPython 0.13 (warning added in "
2520 "8.1), use run_line_magic(magic_name, parameter_s).",
2529 "8.1), use run_line_magic(magic_name, parameter_s).",
2521 DeprecationWarning,
2530 DeprecationWarning,
2522 stacklevel=2,
2531 stacklevel=2,
2523 )
2532 )
2524 # TODO: should we issue a loud deprecation warning here?
2533 # TODO: should we issue a loud deprecation warning here?
2525 magic_name, _, magic_arg_s = arg_s.partition(' ')
2534 magic_name, _, magic_arg_s = arg_s.partition(' ')
2526 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2535 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2527 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2536 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2528
2537
2529 #-------------------------------------------------------------------------
2538 #-------------------------------------------------------------------------
2530 # Things related to macros
2539 # Things related to macros
2531 #-------------------------------------------------------------------------
2540 #-------------------------------------------------------------------------
2532
2541
2533 def define_macro(self, name, themacro):
2542 def define_macro(self, name, themacro):
2534 """Define a new macro
2543 """Define a new macro
2535
2544
2536 Parameters
2545 Parameters
2537 ----------
2546 ----------
2538 name : str
2547 name : str
2539 The name of the macro.
2548 The name of the macro.
2540 themacro : str or Macro
2549 themacro : str or Macro
2541 The action to do upon invoking the macro. If a string, a new
2550 The action to do upon invoking the macro. If a string, a new
2542 Macro object is created by passing the string to it.
2551 Macro object is created by passing the string to it.
2543 """
2552 """
2544
2553
2545 from IPython.core import macro
2554 from IPython.core import macro
2546
2555
2547 if isinstance(themacro, str):
2556 if isinstance(themacro, str):
2548 themacro = macro.Macro(themacro)
2557 themacro = macro.Macro(themacro)
2549 if not isinstance(themacro, macro.Macro):
2558 if not isinstance(themacro, macro.Macro):
2550 raise ValueError('A macro must be a string or a Macro instance.')
2559 raise ValueError('A macro must be a string or a Macro instance.')
2551 self.user_ns[name] = themacro
2560 self.user_ns[name] = themacro
2552
2561
2553 #-------------------------------------------------------------------------
2562 #-------------------------------------------------------------------------
2554 # Things related to the running of system commands
2563 # Things related to the running of system commands
2555 #-------------------------------------------------------------------------
2564 #-------------------------------------------------------------------------
2556
2565
2557 def system_piped(self, cmd):
2566 def system_piped(self, cmd):
2558 """Call the given cmd in a subprocess, piping stdout/err
2567 """Call the given cmd in a subprocess, piping stdout/err
2559
2568
2560 Parameters
2569 Parameters
2561 ----------
2570 ----------
2562 cmd : str
2571 cmd : str
2563 Command to execute (can not end in '&', as background processes are
2572 Command to execute (can not end in '&', as background processes are
2564 not supported. Should not be a command that expects input
2573 not supported. Should not be a command that expects input
2565 other than simple text.
2574 other than simple text.
2566 """
2575 """
2567 if cmd.rstrip().endswith('&'):
2576 if cmd.rstrip().endswith('&'):
2568 # this is *far* from a rigorous test
2577 # this is *far* from a rigorous test
2569 # We do not support backgrounding processes because we either use
2578 # We do not support backgrounding processes because we either use
2570 # pexpect or pipes to read from. Users can always just call
2579 # pexpect or pipes to read from. Users can always just call
2571 # os.system() or use ip.system=ip.system_raw
2580 # os.system() or use ip.system=ip.system_raw
2572 # if they really want a background process.
2581 # if they really want a background process.
2573 raise OSError("Background processes not supported.")
2582 raise OSError("Background processes not supported.")
2574
2583
2575 # we explicitly do NOT return the subprocess status code, because
2584 # we explicitly do NOT return the subprocess status code, because
2576 # a non-None value would trigger :func:`sys.displayhook` calls.
2585 # a non-None value would trigger :func:`sys.displayhook` calls.
2577 # Instead, we store the exit_code in user_ns.
2586 # Instead, we store the exit_code in user_ns.
2578 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2587 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2579
2588
2580 def system_raw(self, cmd):
2589 def system_raw(self, cmd):
2581 """Call the given cmd in a subprocess using os.system on Windows or
2590 """Call the given cmd in a subprocess using os.system on Windows or
2582 subprocess.call using the system shell on other platforms.
2591 subprocess.call using the system shell on other platforms.
2583
2592
2584 Parameters
2593 Parameters
2585 ----------
2594 ----------
2586 cmd : str
2595 cmd : str
2587 Command to execute.
2596 Command to execute.
2588 """
2597 """
2589 cmd = self.var_expand(cmd, depth=1)
2598 cmd = self.var_expand(cmd, depth=1)
2590 # warn if there is an IPython magic alternative.
2599 # warn if there is an IPython magic alternative.
2591 main_cmd = cmd.split()[0]
2600 main_cmd = cmd.split()[0]
2592 has_magic_alternatives = ("pip", "conda", "cd")
2601 has_magic_alternatives = ("pip", "conda", "cd")
2593
2602
2594 if main_cmd in has_magic_alternatives:
2603 if main_cmd in has_magic_alternatives:
2595 warnings.warn(
2604 warnings.warn(
2596 (
2605 (
2597 "You executed the system command !{0} which may not work "
2606 "You executed the system command !{0} which may not work "
2598 "as expected. Try the IPython magic %{0} instead."
2607 "as expected. Try the IPython magic %{0} instead."
2599 ).format(main_cmd)
2608 ).format(main_cmd)
2600 )
2609 )
2601
2610
2602 # protect os.system from UNC paths on Windows, which it can't handle:
2611 # protect os.system from UNC paths on Windows, which it can't handle:
2603 if sys.platform == 'win32':
2612 if sys.platform == 'win32':
2604 from IPython.utils._process_win32 import AvoidUNCPath
2613 from IPython.utils._process_win32 import AvoidUNCPath
2605 with AvoidUNCPath() as path:
2614 with AvoidUNCPath() as path:
2606 if path is not None:
2615 if path is not None:
2607 cmd = '"pushd %s &&"%s' % (path, cmd)
2616 cmd = '"pushd %s &&"%s' % (path, cmd)
2608 try:
2617 try:
2609 ec = os.system(cmd)
2618 ec = os.system(cmd)
2610 except KeyboardInterrupt:
2619 except KeyboardInterrupt:
2611 print('\n' + self.get_exception_only(), file=sys.stderr)
2620 print('\n' + self.get_exception_only(), file=sys.stderr)
2612 ec = -2
2621 ec = -2
2613 else:
2622 else:
2614 # For posix the result of the subprocess.call() below is an exit
2623 # For posix the result of the subprocess.call() below is an exit
2615 # code, which by convention is zero for success, positive for
2624 # code, which by convention is zero for success, positive for
2616 # program failure. Exit codes above 128 are reserved for signals,
2625 # program failure. Exit codes above 128 are reserved for signals,
2617 # and the formula for converting a signal to an exit code is usually
2626 # and the formula for converting a signal to an exit code is usually
2618 # signal_number+128. To more easily differentiate between exit
2627 # signal_number+128. To more easily differentiate between exit
2619 # codes and signals, ipython uses negative numbers. For instance
2628 # codes and signals, ipython uses negative numbers. For instance
2620 # since control-c is signal 2 but exit code 130, ipython's
2629 # since control-c is signal 2 but exit code 130, ipython's
2621 # _exit_code variable will read -2. Note that some shells like
2630 # _exit_code variable will read -2. Note that some shells like
2622 # csh and fish don't follow sh/bash conventions for exit codes.
2631 # csh and fish don't follow sh/bash conventions for exit codes.
2623 executable = os.environ.get('SHELL', None)
2632 executable = os.environ.get('SHELL', None)
2624 try:
2633 try:
2625 # Use env shell instead of default /bin/sh
2634 # Use env shell instead of default /bin/sh
2626 ec = subprocess.call(cmd, shell=True, executable=executable)
2635 ec = subprocess.call(cmd, shell=True, executable=executable)
2627 except KeyboardInterrupt:
2636 except KeyboardInterrupt:
2628 # intercept control-C; a long traceback is not useful here
2637 # intercept control-C; a long traceback is not useful here
2629 print('\n' + self.get_exception_only(), file=sys.stderr)
2638 print('\n' + self.get_exception_only(), file=sys.stderr)
2630 ec = 130
2639 ec = 130
2631 if ec > 128:
2640 if ec > 128:
2632 ec = -(ec - 128)
2641 ec = -(ec - 128)
2633
2642
2634 # We explicitly do NOT return the subprocess status code, because
2643 # We explicitly do NOT return the subprocess status code, because
2635 # a non-None value would trigger :func:`sys.displayhook` calls.
2644 # a non-None value would trigger :func:`sys.displayhook` calls.
2636 # Instead, we store the exit_code in user_ns. Note the semantics
2645 # Instead, we store the exit_code in user_ns. Note the semantics
2637 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2646 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2638 # but raising SystemExit(_exit_code) will give status 254!
2647 # but raising SystemExit(_exit_code) will give status 254!
2639 self.user_ns['_exit_code'] = ec
2648 self.user_ns['_exit_code'] = ec
2640
2649
2641 # use piped system by default, because it is better behaved
2650 # use piped system by default, because it is better behaved
2642 system = system_piped
2651 system = system_piped
2643
2652
2644 def getoutput(self, cmd, split=True, depth=0):
2653 def getoutput(self, cmd, split=True, depth=0):
2645 """Get output (possibly including stderr) from a subprocess.
2654 """Get output (possibly including stderr) from a subprocess.
2646
2655
2647 Parameters
2656 Parameters
2648 ----------
2657 ----------
2649 cmd : str
2658 cmd : str
2650 Command to execute (can not end in '&', as background processes are
2659 Command to execute (can not end in '&', as background processes are
2651 not supported.
2660 not supported.
2652 split : bool, optional
2661 split : bool, optional
2653 If True, split the output into an IPython SList. Otherwise, an
2662 If True, split the output into an IPython SList. Otherwise, an
2654 IPython LSString is returned. These are objects similar to normal
2663 IPython LSString is returned. These are objects similar to normal
2655 lists and strings, with a few convenience attributes for easier
2664 lists and strings, with a few convenience attributes for easier
2656 manipulation of line-based output. You can use '?' on them for
2665 manipulation of line-based output. You can use '?' on them for
2657 details.
2666 details.
2658 depth : int, optional
2667 depth : int, optional
2659 How many frames above the caller are the local variables which should
2668 How many frames above the caller are the local variables which should
2660 be expanded in the command string? The default (0) assumes that the
2669 be expanded in the command string? The default (0) assumes that the
2661 expansion variables are in the stack frame calling this function.
2670 expansion variables are in the stack frame calling this function.
2662 """
2671 """
2663 if cmd.rstrip().endswith('&'):
2672 if cmd.rstrip().endswith('&'):
2664 # this is *far* from a rigorous test
2673 # this is *far* from a rigorous test
2665 raise OSError("Background processes not supported.")
2674 raise OSError("Background processes not supported.")
2666 out = getoutput(self.var_expand(cmd, depth=depth+1))
2675 out = getoutput(self.var_expand(cmd, depth=depth+1))
2667 if split:
2676 if split:
2668 out = SList(out.splitlines())
2677 out = SList(out.splitlines())
2669 else:
2678 else:
2670 out = LSString(out)
2679 out = LSString(out)
2671 return out
2680 return out
2672
2681
2673 #-------------------------------------------------------------------------
2682 #-------------------------------------------------------------------------
2674 # Things related to aliases
2683 # Things related to aliases
2675 #-------------------------------------------------------------------------
2684 #-------------------------------------------------------------------------
2676
2685
2677 def init_alias(self):
2686 def init_alias(self):
2678 self.alias_manager = AliasManager(shell=self, parent=self)
2687 self.alias_manager = AliasManager(shell=self, parent=self)
2679 self.configurables.append(self.alias_manager)
2688 self.configurables.append(self.alias_manager)
2680
2689
2681 #-------------------------------------------------------------------------
2690 #-------------------------------------------------------------------------
2682 # Things related to extensions
2691 # Things related to extensions
2683 #-------------------------------------------------------------------------
2692 #-------------------------------------------------------------------------
2684
2693
2685 def init_extension_manager(self):
2694 def init_extension_manager(self):
2686 self.extension_manager = ExtensionManager(shell=self, parent=self)
2695 self.extension_manager = ExtensionManager(shell=self, parent=self)
2687 self.configurables.append(self.extension_manager)
2696 self.configurables.append(self.extension_manager)
2688
2697
2689 #-------------------------------------------------------------------------
2698 #-------------------------------------------------------------------------
2690 # Things related to payloads
2699 # Things related to payloads
2691 #-------------------------------------------------------------------------
2700 #-------------------------------------------------------------------------
2692
2701
2693 def init_payload(self):
2702 def init_payload(self):
2694 self.payload_manager = PayloadManager(parent=self)
2703 self.payload_manager = PayloadManager(parent=self)
2695 self.configurables.append(self.payload_manager)
2704 self.configurables.append(self.payload_manager)
2696
2705
2697 #-------------------------------------------------------------------------
2706 #-------------------------------------------------------------------------
2698 # Things related to the prefilter
2707 # Things related to the prefilter
2699 #-------------------------------------------------------------------------
2708 #-------------------------------------------------------------------------
2700
2709
2701 def init_prefilter(self):
2710 def init_prefilter(self):
2702 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2711 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2703 self.configurables.append(self.prefilter_manager)
2712 self.configurables.append(self.prefilter_manager)
2704 # Ultimately this will be refactored in the new interpreter code, but
2713 # Ultimately this will be refactored in the new interpreter code, but
2705 # for now, we should expose the main prefilter method (there's legacy
2714 # for now, we should expose the main prefilter method (there's legacy
2706 # code out there that may rely on this).
2715 # code out there that may rely on this).
2707 self.prefilter = self.prefilter_manager.prefilter_lines
2716 self.prefilter = self.prefilter_manager.prefilter_lines
2708
2717
2709 def auto_rewrite_input(self, cmd):
2718 def auto_rewrite_input(self, cmd):
2710 """Print to the screen the rewritten form of the user's command.
2719 """Print to the screen the rewritten form of the user's command.
2711
2720
2712 This shows visual feedback by rewriting input lines that cause
2721 This shows visual feedback by rewriting input lines that cause
2713 automatic calling to kick in, like::
2722 automatic calling to kick in, like::
2714
2723
2715 /f x
2724 /f x
2716
2725
2717 into::
2726 into::
2718
2727
2719 ------> f(x)
2728 ------> f(x)
2720
2729
2721 after the user's input prompt. This helps the user understand that the
2730 after the user's input prompt. This helps the user understand that the
2722 input line was transformed automatically by IPython.
2731 input line was transformed automatically by IPython.
2723 """
2732 """
2724 if not self.show_rewritten_input:
2733 if not self.show_rewritten_input:
2725 return
2734 return
2726
2735
2727 # This is overridden in TerminalInteractiveShell to use fancy prompts
2736 # This is overridden in TerminalInteractiveShell to use fancy prompts
2728 print("------> " + cmd)
2737 print("------> " + cmd)
2729
2738
2730 #-------------------------------------------------------------------------
2739 #-------------------------------------------------------------------------
2731 # Things related to extracting values/expressions from kernel and user_ns
2740 # Things related to extracting values/expressions from kernel and user_ns
2732 #-------------------------------------------------------------------------
2741 #-------------------------------------------------------------------------
2733
2742
2734 def _user_obj_error(self):
2743 def _user_obj_error(self):
2735 """return simple exception dict
2744 """return simple exception dict
2736
2745
2737 for use in user_expressions
2746 for use in user_expressions
2738 """
2747 """
2739
2748
2740 etype, evalue, tb = self._get_exc_info()
2749 etype, evalue, tb = self._get_exc_info()
2741 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2750 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2742
2751
2743 exc_info = {
2752 exc_info = {
2744 "status": "error",
2753 "status": "error",
2745 "traceback": stb,
2754 "traceback": stb,
2746 "ename": etype.__name__,
2755 "ename": etype.__name__,
2747 "evalue": py3compat.safe_unicode(evalue),
2756 "evalue": py3compat.safe_unicode(evalue),
2748 }
2757 }
2749
2758
2750 return exc_info
2759 return exc_info
2751
2760
2752 def _format_user_obj(self, obj):
2761 def _format_user_obj(self, obj):
2753 """format a user object to display dict
2762 """format a user object to display dict
2754
2763
2755 for use in user_expressions
2764 for use in user_expressions
2756 """
2765 """
2757
2766
2758 data, md = self.display_formatter.format(obj)
2767 data, md = self.display_formatter.format(obj)
2759 value = {
2768 value = {
2760 'status' : 'ok',
2769 'status' : 'ok',
2761 'data' : data,
2770 'data' : data,
2762 'metadata' : md,
2771 'metadata' : md,
2763 }
2772 }
2764 return value
2773 return value
2765
2774
2766 def user_expressions(self, expressions):
2775 def user_expressions(self, expressions):
2767 """Evaluate a dict of expressions in the user's namespace.
2776 """Evaluate a dict of expressions in the user's namespace.
2768
2777
2769 Parameters
2778 Parameters
2770 ----------
2779 ----------
2771 expressions : dict
2780 expressions : dict
2772 A dict with string keys and string values. The expression values
2781 A dict with string keys and string values. The expression values
2773 should be valid Python expressions, each of which will be evaluated
2782 should be valid Python expressions, each of which will be evaluated
2774 in the user namespace.
2783 in the user namespace.
2775
2784
2776 Returns
2785 Returns
2777 -------
2786 -------
2778 A dict, keyed like the input expressions dict, with the rich mime-typed
2787 A dict, keyed like the input expressions dict, with the rich mime-typed
2779 display_data of each value.
2788 display_data of each value.
2780 """
2789 """
2781 out = {}
2790 out = {}
2782 user_ns = self.user_ns
2791 user_ns = self.user_ns
2783 global_ns = self.user_global_ns
2792 global_ns = self.user_global_ns
2784
2793
2785 for key, expr in expressions.items():
2794 for key, expr in expressions.items():
2786 try:
2795 try:
2787 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2796 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2788 except:
2797 except:
2789 value = self._user_obj_error()
2798 value = self._user_obj_error()
2790 out[key] = value
2799 out[key] = value
2791 return out
2800 return out
2792
2801
2793 #-------------------------------------------------------------------------
2802 #-------------------------------------------------------------------------
2794 # Things related to the running of code
2803 # Things related to the running of code
2795 #-------------------------------------------------------------------------
2804 #-------------------------------------------------------------------------
2796
2805
2797 def ex(self, cmd):
2806 def ex(self, cmd):
2798 """Execute a normal python statement in user namespace."""
2807 """Execute a normal python statement in user namespace."""
2799 with self.builtin_trap:
2808 with self.builtin_trap:
2800 exec(cmd, self.user_global_ns, self.user_ns)
2809 exec(cmd, self.user_global_ns, self.user_ns)
2801
2810
2802 def ev(self, expr):
2811 def ev(self, expr):
2803 """Evaluate python expression expr in user namespace.
2812 """Evaluate python expression expr in user namespace.
2804
2813
2805 Returns the result of evaluation
2814 Returns the result of evaluation
2806 """
2815 """
2807 with self.builtin_trap:
2816 with self.builtin_trap:
2808 return eval(expr, self.user_global_ns, self.user_ns)
2817 return eval(expr, self.user_global_ns, self.user_ns)
2809
2818
2810 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2819 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2811 """A safe version of the builtin execfile().
2820 """A safe version of the builtin execfile().
2812
2821
2813 This version will never throw an exception, but instead print
2822 This version will never throw an exception, but instead print
2814 helpful error messages to the screen. This only works on pure
2823 helpful error messages to the screen. This only works on pure
2815 Python files with the .py extension.
2824 Python files with the .py extension.
2816
2825
2817 Parameters
2826 Parameters
2818 ----------
2827 ----------
2819 fname : string
2828 fname : string
2820 The name of the file to be executed.
2829 The name of the file to be executed.
2821 *where : tuple
2830 *where : tuple
2822 One or two namespaces, passed to execfile() as (globals,locals).
2831 One or two namespaces, passed to execfile() as (globals,locals).
2823 If only one is given, it is passed as both.
2832 If only one is given, it is passed as both.
2824 exit_ignore : bool (False)
2833 exit_ignore : bool (False)
2825 If True, then silence SystemExit for non-zero status (it is always
2834 If True, then silence SystemExit for non-zero status (it is always
2826 silenced for zero status, as it is so common).
2835 silenced for zero status, as it is so common).
2827 raise_exceptions : bool (False)
2836 raise_exceptions : bool (False)
2828 If True raise exceptions everywhere. Meant for testing.
2837 If True raise exceptions everywhere. Meant for testing.
2829 shell_futures : bool (False)
2838 shell_futures : bool (False)
2830 If True, the code will share future statements with the interactive
2839 If True, the code will share future statements with the interactive
2831 shell. It will both be affected by previous __future__ imports, and
2840 shell. It will both be affected by previous __future__ imports, and
2832 any __future__ imports in the code will affect the shell. If False,
2841 any __future__ imports in the code will affect the shell. If False,
2833 __future__ imports are not shared in either direction.
2842 __future__ imports are not shared in either direction.
2834
2843
2835 """
2844 """
2836 fname = Path(fname).expanduser().resolve()
2845 fname = Path(fname).expanduser().resolve()
2837
2846
2838 # Make sure we can open the file
2847 # Make sure we can open the file
2839 try:
2848 try:
2840 with fname.open("rb"):
2849 with fname.open("rb"):
2841 pass
2850 pass
2842 except:
2851 except:
2843 warn('Could not open file <%s> for safe execution.' % fname)
2852 warn('Could not open file <%s> for safe execution.' % fname)
2844 return
2853 return
2845
2854
2846 # Find things also in current directory. This is needed to mimic the
2855 # Find things also in current directory. This is needed to mimic the
2847 # behavior of running a script from the system command line, where
2856 # behavior of running a script from the system command line, where
2848 # Python inserts the script's directory into sys.path
2857 # Python inserts the script's directory into sys.path
2849 dname = str(fname.parent)
2858 dname = str(fname.parent)
2850
2859
2851 with prepended_to_syspath(dname), self.builtin_trap:
2860 with prepended_to_syspath(dname), self.builtin_trap:
2852 try:
2861 try:
2853 glob, loc = (where + (None, ))[:2]
2862 glob, loc = (where + (None, ))[:2]
2854 py3compat.execfile(
2863 py3compat.execfile(
2855 fname, glob, loc,
2864 fname, glob, loc,
2856 self.compile if shell_futures else None)
2865 self.compile if shell_futures else None)
2857 except SystemExit as status:
2866 except SystemExit as status:
2858 # If the call was made with 0 or None exit status (sys.exit(0)
2867 # If the call was made with 0 or None exit status (sys.exit(0)
2859 # or sys.exit() ), don't bother showing a traceback, as both of
2868 # or sys.exit() ), don't bother showing a traceback, as both of
2860 # these are considered normal by the OS:
2869 # these are considered normal by the OS:
2861 # > python -c'import sys;sys.exit(0)'; echo $?
2870 # > python -c'import sys;sys.exit(0)'; echo $?
2862 # 0
2871 # 0
2863 # > python -c'import sys;sys.exit()'; echo $?
2872 # > python -c'import sys;sys.exit()'; echo $?
2864 # 0
2873 # 0
2865 # For other exit status, we show the exception unless
2874 # For other exit status, we show the exception unless
2866 # explicitly silenced, but only in short form.
2875 # explicitly silenced, but only in short form.
2867 if status.code:
2876 if status.code:
2868 if raise_exceptions:
2877 if raise_exceptions:
2869 raise
2878 raise
2870 if not exit_ignore:
2879 if not exit_ignore:
2871 self.showtraceback(exception_only=True)
2880 self.showtraceback(exception_only=True)
2872 except:
2881 except:
2873 if raise_exceptions:
2882 if raise_exceptions:
2874 raise
2883 raise
2875 # tb offset is 2 because we wrap execfile
2884 # tb offset is 2 because we wrap execfile
2876 self.showtraceback(tb_offset=2)
2885 self.showtraceback(tb_offset=2)
2877
2886
2878 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2887 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2879 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2888 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2880
2889
2881 Parameters
2890 Parameters
2882 ----------
2891 ----------
2883 fname : str
2892 fname : str
2884 The name of the file to execute. The filename must have a
2893 The name of the file to execute. The filename must have a
2885 .ipy or .ipynb extension.
2894 .ipy or .ipynb extension.
2886 shell_futures : bool (False)
2895 shell_futures : bool (False)
2887 If True, the code will share future statements with the interactive
2896 If True, the code will share future statements with the interactive
2888 shell. It will both be affected by previous __future__ imports, and
2897 shell. It will both be affected by previous __future__ imports, and
2889 any __future__ imports in the code will affect the shell. If False,
2898 any __future__ imports in the code will affect the shell. If False,
2890 __future__ imports are not shared in either direction.
2899 __future__ imports are not shared in either direction.
2891 raise_exceptions : bool (False)
2900 raise_exceptions : bool (False)
2892 If True raise exceptions everywhere. Meant for testing.
2901 If True raise exceptions everywhere. Meant for testing.
2893 """
2902 """
2894 fname = Path(fname).expanduser().resolve()
2903 fname = Path(fname).expanduser().resolve()
2895
2904
2896 # Make sure we can open the file
2905 # Make sure we can open the file
2897 try:
2906 try:
2898 with fname.open("rb"):
2907 with fname.open("rb"):
2899 pass
2908 pass
2900 except:
2909 except:
2901 warn('Could not open file <%s> for safe execution.' % fname)
2910 warn('Could not open file <%s> for safe execution.' % fname)
2902 return
2911 return
2903
2912
2904 # Find things also in current directory. This is needed to mimic the
2913 # Find things also in current directory. This is needed to mimic the
2905 # behavior of running a script from the system command line, where
2914 # behavior of running a script from the system command line, where
2906 # Python inserts the script's directory into sys.path
2915 # Python inserts the script's directory into sys.path
2907 dname = str(fname.parent)
2916 dname = str(fname.parent)
2908
2917
2909 def get_cells():
2918 def get_cells():
2910 """generator for sequence of code blocks to run"""
2919 """generator for sequence of code blocks to run"""
2911 if fname.suffix == ".ipynb":
2920 if fname.suffix == ".ipynb":
2912 from nbformat import read
2921 from nbformat import read
2913 nb = read(fname, as_version=4)
2922 nb = read(fname, as_version=4)
2914 if not nb.cells:
2923 if not nb.cells:
2915 return
2924 return
2916 for cell in nb.cells:
2925 for cell in nb.cells:
2917 if cell.cell_type == 'code':
2926 if cell.cell_type == 'code':
2918 yield cell.source
2927 yield cell.source
2919 else:
2928 else:
2920 yield fname.read_text(encoding="utf-8")
2929 yield fname.read_text(encoding="utf-8")
2921
2930
2922 with prepended_to_syspath(dname):
2931 with prepended_to_syspath(dname):
2923 try:
2932 try:
2924 for cell in get_cells():
2933 for cell in get_cells():
2925 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2934 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2926 if raise_exceptions:
2935 if raise_exceptions:
2927 result.raise_error()
2936 result.raise_error()
2928 elif not result.success:
2937 elif not result.success:
2929 break
2938 break
2930 except:
2939 except:
2931 if raise_exceptions:
2940 if raise_exceptions:
2932 raise
2941 raise
2933 self.showtraceback()
2942 self.showtraceback()
2934 warn('Unknown failure executing file: <%s>' % fname)
2943 warn('Unknown failure executing file: <%s>' % fname)
2935
2944
2936 def safe_run_module(self, mod_name, where):
2945 def safe_run_module(self, mod_name, where):
2937 """A safe version of runpy.run_module().
2946 """A safe version of runpy.run_module().
2938
2947
2939 This version will never throw an exception, but instead print
2948 This version will never throw an exception, but instead print
2940 helpful error messages to the screen.
2949 helpful error messages to the screen.
2941
2950
2942 `SystemExit` exceptions with status code 0 or None are ignored.
2951 `SystemExit` exceptions with status code 0 or None are ignored.
2943
2952
2944 Parameters
2953 Parameters
2945 ----------
2954 ----------
2946 mod_name : string
2955 mod_name : string
2947 The name of the module to be executed.
2956 The name of the module to be executed.
2948 where : dict
2957 where : dict
2949 The globals namespace.
2958 The globals namespace.
2950 """
2959 """
2951 try:
2960 try:
2952 try:
2961 try:
2953 where.update(
2962 where.update(
2954 runpy.run_module(str(mod_name), run_name="__main__",
2963 runpy.run_module(str(mod_name), run_name="__main__",
2955 alter_sys=True)
2964 alter_sys=True)
2956 )
2965 )
2957 except SystemExit as status:
2966 except SystemExit as status:
2958 if status.code:
2967 if status.code:
2959 raise
2968 raise
2960 except:
2969 except:
2961 self.showtraceback()
2970 self.showtraceback()
2962 warn('Unknown failure executing module: <%s>' % mod_name)
2971 warn('Unknown failure executing module: <%s>' % mod_name)
2963
2972
2964 def run_cell(
2973 def run_cell(
2965 self,
2974 self,
2966 raw_cell,
2975 raw_cell,
2967 store_history=False,
2976 store_history=False,
2968 silent=False,
2977 silent=False,
2969 shell_futures=True,
2978 shell_futures=True,
2970 cell_id=None,
2979 cell_id=None,
2971 ):
2980 ):
2972 """Run a complete IPython cell.
2981 """Run a complete IPython cell.
2973
2982
2974 Parameters
2983 Parameters
2975 ----------
2984 ----------
2976 raw_cell : str
2985 raw_cell : str
2977 The code (including IPython code such as %magic functions) to run.
2986 The code (including IPython code such as %magic functions) to run.
2978 store_history : bool
2987 store_history : bool
2979 If True, the raw and translated cell will be stored in IPython's
2988 If True, the raw and translated cell will be stored in IPython's
2980 history. For user code calling back into IPython's machinery, this
2989 history. For user code calling back into IPython's machinery, this
2981 should be set to False.
2990 should be set to False.
2982 silent : bool
2991 silent : bool
2983 If True, avoid side-effects, such as implicit displayhooks and
2992 If True, avoid side-effects, such as implicit displayhooks and
2984 and logging. silent=True forces store_history=False.
2993 and logging. silent=True forces store_history=False.
2985 shell_futures : bool
2994 shell_futures : bool
2986 If True, the code will share future statements with the interactive
2995 If True, the code will share future statements with the interactive
2987 shell. It will both be affected by previous __future__ imports, and
2996 shell. It will both be affected by previous __future__ imports, and
2988 any __future__ imports in the code will affect the shell. If False,
2997 any __future__ imports in the code will affect the shell. If False,
2989 __future__ imports are not shared in either direction.
2998 __future__ imports are not shared in either direction.
2990
2999
2991 Returns
3000 Returns
2992 -------
3001 -------
2993 result : :class:`ExecutionResult`
3002 result : :class:`ExecutionResult`
2994 """
3003 """
2995 result = None
3004 result = None
2996 try:
3005 try:
2997 result = self._run_cell(
3006 result = self._run_cell(
2998 raw_cell, store_history, silent, shell_futures, cell_id
3007 raw_cell, store_history, silent, shell_futures, cell_id
2999 )
3008 )
3000 finally:
3009 finally:
3001 self.events.trigger('post_execute')
3010 self.events.trigger('post_execute')
3002 if not silent:
3011 if not silent:
3003 self.events.trigger('post_run_cell', result)
3012 self.events.trigger('post_run_cell', result)
3004 return result
3013 return result
3005
3014
3006 def _run_cell(
3015 def _run_cell(
3007 self,
3016 self,
3008 raw_cell: str,
3017 raw_cell: str,
3009 store_history: bool,
3018 store_history: bool,
3010 silent: bool,
3019 silent: bool,
3011 shell_futures: bool,
3020 shell_futures: bool,
3012 cell_id: str,
3021 cell_id: str,
3013 ) -> ExecutionResult:
3022 ) -> ExecutionResult:
3014 """Internal method to run a complete IPython cell."""
3023 """Internal method to run a complete IPython cell."""
3015
3024
3016 # we need to avoid calling self.transform_cell multiple time on the same thing
3025 # we need to avoid calling self.transform_cell multiple time on the same thing
3017 # so we need to store some results:
3026 # so we need to store some results:
3018 preprocessing_exc_tuple = None
3027 preprocessing_exc_tuple = None
3019 try:
3028 try:
3020 transformed_cell = self.transform_cell(raw_cell)
3029 transformed_cell = self.transform_cell(raw_cell)
3021 except Exception:
3030 except Exception:
3022 transformed_cell = raw_cell
3031 transformed_cell = raw_cell
3023 preprocessing_exc_tuple = sys.exc_info()
3032 preprocessing_exc_tuple = sys.exc_info()
3024
3033
3025 assert transformed_cell is not None
3034 assert transformed_cell is not None
3026 coro = self.run_cell_async(
3035 coro = self.run_cell_async(
3027 raw_cell,
3036 raw_cell,
3028 store_history=store_history,
3037 store_history=store_history,
3029 silent=silent,
3038 silent=silent,
3030 shell_futures=shell_futures,
3039 shell_futures=shell_futures,
3031 transformed_cell=transformed_cell,
3040 transformed_cell=transformed_cell,
3032 preprocessing_exc_tuple=preprocessing_exc_tuple,
3041 preprocessing_exc_tuple=preprocessing_exc_tuple,
3033 cell_id=cell_id,
3042 cell_id=cell_id,
3034 )
3043 )
3035
3044
3036 # run_cell_async is async, but may not actually need an eventloop.
3045 # run_cell_async is async, but may not actually need an eventloop.
3037 # when this is the case, we want to run it using the pseudo_sync_runner
3046 # when this is the case, we want to run it using the pseudo_sync_runner
3038 # so that code can invoke eventloops (for example via the %run , and
3047 # so that code can invoke eventloops (for example via the %run , and
3039 # `%paste` magic.
3048 # `%paste` magic.
3040 if self.trio_runner:
3049 if self.trio_runner:
3041 runner = self.trio_runner
3050 runner = self.trio_runner
3042 elif self.should_run_async(
3051 elif self.should_run_async(
3043 raw_cell,
3052 raw_cell,
3044 transformed_cell=transformed_cell,
3053 transformed_cell=transformed_cell,
3045 preprocessing_exc_tuple=preprocessing_exc_tuple,
3054 preprocessing_exc_tuple=preprocessing_exc_tuple,
3046 ):
3055 ):
3047 runner = self.loop_runner
3056 runner = self.loop_runner
3048 else:
3057 else:
3049 runner = _pseudo_sync_runner
3058 runner = _pseudo_sync_runner
3050
3059
3051 try:
3060 try:
3052 result = runner(coro)
3061 result = runner(coro)
3053 except BaseException as e:
3062 except BaseException as e:
3054 info = ExecutionInfo(
3063 info = ExecutionInfo(
3055 raw_cell, store_history, silent, shell_futures, cell_id
3064 raw_cell, store_history, silent, shell_futures, cell_id
3056 )
3065 )
3057 result = ExecutionResult(info)
3066 result = ExecutionResult(info)
3058 result.error_in_exec = e
3067 result.error_in_exec = e
3059 self.showtraceback(running_compiled_code=True)
3068 self.showtraceback(running_compiled_code=True)
3060 finally:
3069 finally:
3061 return result
3070 return result
3062
3071
3063 def should_run_async(
3072 def should_run_async(
3064 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
3073 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
3065 ) -> bool:
3074 ) -> bool:
3066 """Return whether a cell should be run asynchronously via a coroutine runner
3075 """Return whether a cell should be run asynchronously via a coroutine runner
3067
3076
3068 Parameters
3077 Parameters
3069 ----------
3078 ----------
3070 raw_cell : str
3079 raw_cell : str
3071 The code to be executed
3080 The code to be executed
3072
3081
3073 Returns
3082 Returns
3074 -------
3083 -------
3075 result: bool
3084 result: bool
3076 Whether the code needs to be run with a coroutine runner or not
3085 Whether the code needs to be run with a coroutine runner or not
3077 .. versionadded:: 7.0
3086 .. versionadded:: 7.0
3078 """
3087 """
3079 if not self.autoawait:
3088 if not self.autoawait:
3080 return False
3089 return False
3081 if preprocessing_exc_tuple is not None:
3090 if preprocessing_exc_tuple is not None:
3082 return False
3091 return False
3083 assert preprocessing_exc_tuple is None
3092 assert preprocessing_exc_tuple is None
3084 if transformed_cell is None:
3093 if transformed_cell is None:
3085 warnings.warn(
3094 warnings.warn(
3086 "`should_run_async` will not call `transform_cell`"
3095 "`should_run_async` will not call `transform_cell`"
3087 " automatically in the future. Please pass the result to"
3096 " automatically in the future. Please pass the result to"
3088 " `transformed_cell` argument and any exception that happen"
3097 " `transformed_cell` argument and any exception that happen"
3089 " during the"
3098 " during the"
3090 "transform in `preprocessing_exc_tuple` in"
3099 "transform in `preprocessing_exc_tuple` in"
3091 " IPython 7.17 and above.",
3100 " IPython 7.17 and above.",
3092 DeprecationWarning,
3101 DeprecationWarning,
3093 stacklevel=2,
3102 stacklevel=2,
3094 )
3103 )
3095 try:
3104 try:
3096 cell = self.transform_cell(raw_cell)
3105 cell = self.transform_cell(raw_cell)
3097 except Exception:
3106 except Exception:
3098 # any exception during transform will be raised
3107 # any exception during transform will be raised
3099 # prior to execution
3108 # prior to execution
3100 return False
3109 return False
3101 else:
3110 else:
3102 cell = transformed_cell
3111 cell = transformed_cell
3103 return _should_be_async(cell)
3112 return _should_be_async(cell)
3104
3113
3105 async def run_cell_async(
3114 async def run_cell_async(
3106 self,
3115 self,
3107 raw_cell: str,
3116 raw_cell: str,
3108 store_history=False,
3117 store_history=False,
3109 silent=False,
3118 silent=False,
3110 shell_futures=True,
3119 shell_futures=True,
3111 *,
3120 *,
3112 transformed_cell: Optional[str] = None,
3121 transformed_cell: Optional[str] = None,
3113 preprocessing_exc_tuple: Optional[AnyType] = None,
3122 preprocessing_exc_tuple: Optional[AnyType] = None,
3114 cell_id=None,
3123 cell_id=None,
3115 ) -> ExecutionResult:
3124 ) -> ExecutionResult:
3116 """Run a complete IPython cell asynchronously.
3125 """Run a complete IPython cell asynchronously.
3117
3126
3118 Parameters
3127 Parameters
3119 ----------
3128 ----------
3120 raw_cell : str
3129 raw_cell : str
3121 The code (including IPython code such as %magic functions) to run.
3130 The code (including IPython code such as %magic functions) to run.
3122 store_history : bool
3131 store_history : bool
3123 If True, the raw and translated cell will be stored in IPython's
3132 If True, the raw and translated cell will be stored in IPython's
3124 history. For user code calling back into IPython's machinery, this
3133 history. For user code calling back into IPython's machinery, this
3125 should be set to False.
3134 should be set to False.
3126 silent : bool
3135 silent : bool
3127 If True, avoid side-effects, such as implicit displayhooks and
3136 If True, avoid side-effects, such as implicit displayhooks and
3128 and logging. silent=True forces store_history=False.
3137 and logging. silent=True forces store_history=False.
3129 shell_futures : bool
3138 shell_futures : bool
3130 If True, the code will share future statements with the interactive
3139 If True, the code will share future statements with the interactive
3131 shell. It will both be affected by previous __future__ imports, and
3140 shell. It will both be affected by previous __future__ imports, and
3132 any __future__ imports in the code will affect the shell. If False,
3141 any __future__ imports in the code will affect the shell. If False,
3133 __future__ imports are not shared in either direction.
3142 __future__ imports are not shared in either direction.
3134 transformed_cell: str
3143 transformed_cell: str
3135 cell that was passed through transformers
3144 cell that was passed through transformers
3136 preprocessing_exc_tuple:
3145 preprocessing_exc_tuple:
3137 trace if the transformation failed.
3146 trace if the transformation failed.
3138
3147
3139 Returns
3148 Returns
3140 -------
3149 -------
3141 result : :class:`ExecutionResult`
3150 result : :class:`ExecutionResult`
3142
3151
3143 .. versionadded:: 7.0
3152 .. versionadded:: 7.0
3144 """
3153 """
3145 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id)
3154 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id)
3146 result = ExecutionResult(info)
3155 result = ExecutionResult(info)
3147
3156
3148 if (not raw_cell) or raw_cell.isspace():
3157 if (not raw_cell) or raw_cell.isspace():
3149 self.last_execution_succeeded = True
3158 self.last_execution_succeeded = True
3150 self.last_execution_result = result
3159 self.last_execution_result = result
3151 return result
3160 return result
3152
3161
3153 if silent:
3162 if silent:
3154 store_history = False
3163 store_history = False
3155
3164
3156 if store_history:
3165 if store_history:
3157 result.execution_count = self.execution_count
3166 result.execution_count = self.execution_count
3158
3167
3159 def error_before_exec(value):
3168 def error_before_exec(value):
3160 if store_history:
3169 if store_history:
3161 self.execution_count += 1
3170 self.execution_count += 1
3162 result.error_before_exec = value
3171 result.error_before_exec = value
3163 self.last_execution_succeeded = False
3172 self.last_execution_succeeded = False
3164 self.last_execution_result = result
3173 self.last_execution_result = result
3165 return result
3174 return result
3166
3175
3167 self.events.trigger('pre_execute')
3176 self.events.trigger('pre_execute')
3168 if not silent:
3177 if not silent:
3169 self.events.trigger('pre_run_cell', info)
3178 self.events.trigger('pre_run_cell', info)
3170
3179
3171 if transformed_cell is None:
3180 if transformed_cell is None:
3172 warnings.warn(
3181 warnings.warn(
3173 "`run_cell_async` will not call `transform_cell`"
3182 "`run_cell_async` will not call `transform_cell`"
3174 " automatically in the future. Please pass the result to"
3183 " automatically in the future. Please pass the result to"
3175 " `transformed_cell` argument and any exception that happen"
3184 " `transformed_cell` argument and any exception that happen"
3176 " during the"
3185 " during the"
3177 "transform in `preprocessing_exc_tuple` in"
3186 "transform in `preprocessing_exc_tuple` in"
3178 " IPython 7.17 and above.",
3187 " IPython 7.17 and above.",
3179 DeprecationWarning,
3188 DeprecationWarning,
3180 stacklevel=2,
3189 stacklevel=2,
3181 )
3190 )
3182 # If any of our input transformation (input_transformer_manager or
3191 # If any of our input transformation (input_transformer_manager or
3183 # prefilter_manager) raises an exception, we store it in this variable
3192 # prefilter_manager) raises an exception, we store it in this variable
3184 # so that we can display the error after logging the input and storing
3193 # so that we can display the error after logging the input and storing
3185 # it in the history.
3194 # it in the history.
3186 try:
3195 try:
3187 cell = self.transform_cell(raw_cell)
3196 cell = self.transform_cell(raw_cell)
3188 except Exception:
3197 except Exception:
3189 preprocessing_exc_tuple = sys.exc_info()
3198 preprocessing_exc_tuple = sys.exc_info()
3190 cell = raw_cell # cell has to exist so it can be stored/logged
3199 cell = raw_cell # cell has to exist so it can be stored/logged
3191 else:
3200 else:
3192 preprocessing_exc_tuple = None
3201 preprocessing_exc_tuple = None
3193 else:
3202 else:
3194 if preprocessing_exc_tuple is None:
3203 if preprocessing_exc_tuple is None:
3195 cell = transformed_cell
3204 cell = transformed_cell
3196 else:
3205 else:
3197 cell = raw_cell
3206 cell = raw_cell
3198
3207
3199 # Do NOT store paste/cpaste magic history
3208 # Do NOT store paste/cpaste magic history
3200 if "get_ipython().run_line_magic(" in cell and "paste" in cell:
3209 if "get_ipython().run_line_magic(" in cell and "paste" in cell:
3201 store_history = False
3210 store_history = False
3202
3211
3203 # Store raw and processed history
3212 # Store raw and processed history
3204 if store_history:
3213 if store_history:
3205 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3214 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3206 if not silent:
3215 if not silent:
3207 self.logger.log(cell, raw_cell)
3216 self.logger.log(cell, raw_cell)
3208
3217
3209 # Display the exception if input processing failed.
3218 # Display the exception if input processing failed.
3210 if preprocessing_exc_tuple is not None:
3219 if preprocessing_exc_tuple is not None:
3211 self.showtraceback(preprocessing_exc_tuple)
3220 self.showtraceback(preprocessing_exc_tuple)
3212 if store_history:
3221 if store_history:
3213 self.execution_count += 1
3222 self.execution_count += 1
3214 return error_before_exec(preprocessing_exc_tuple[1])
3223 return error_before_exec(preprocessing_exc_tuple[1])
3215
3224
3216 # Our own compiler remembers the __future__ environment. If we want to
3225 # Our own compiler remembers the __future__ environment. If we want to
3217 # run code with a separate __future__ environment, use the default
3226 # run code with a separate __future__ environment, use the default
3218 # compiler
3227 # compiler
3219 compiler = self.compile if shell_futures else self.compiler_class()
3228 compiler = self.compile if shell_futures else self.compiler_class()
3220
3229
3221 _run_async = False
3230 _run_async = False
3222
3231
3223 with self.builtin_trap:
3232 with self.builtin_trap:
3224 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3233 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3225
3234
3226 with self.display_trap:
3235 with self.display_trap:
3227 # Compile to bytecode
3236 # Compile to bytecode
3228 try:
3237 try:
3229 code_ast = compiler.ast_parse(cell, filename=cell_name)
3238 code_ast = compiler.ast_parse(cell, filename=cell_name)
3230 except self.custom_exceptions as e:
3239 except self.custom_exceptions as e:
3231 etype, value, tb = sys.exc_info()
3240 etype, value, tb = sys.exc_info()
3232 self.CustomTB(etype, value, tb)
3241 self.CustomTB(etype, value, tb)
3233 return error_before_exec(e)
3242 return error_before_exec(e)
3234 except IndentationError as e:
3243 except IndentationError as e:
3235 self.showindentationerror()
3244 self.showindentationerror()
3236 return error_before_exec(e)
3245 return error_before_exec(e)
3237 except (OverflowError, SyntaxError, ValueError, TypeError,
3246 except (OverflowError, SyntaxError, ValueError, TypeError,
3238 MemoryError) as e:
3247 MemoryError) as e:
3239 self.showsyntaxerror()
3248 self.showsyntaxerror()
3240 return error_before_exec(e)
3249 return error_before_exec(e)
3241
3250
3242 # Apply AST transformations
3251 # Apply AST transformations
3243 try:
3252 try:
3244 code_ast = self.transform_ast(code_ast)
3253 code_ast = self.transform_ast(code_ast)
3245 except InputRejected as e:
3254 except InputRejected as e:
3246 self.showtraceback()
3255 self.showtraceback()
3247 return error_before_exec(e)
3256 return error_before_exec(e)
3248
3257
3249 # Give the displayhook a reference to our ExecutionResult so it
3258 # Give the displayhook a reference to our ExecutionResult so it
3250 # can fill in the output value.
3259 # can fill in the output value.
3251 self.displayhook.exec_result = result
3260 self.displayhook.exec_result = result
3252
3261
3253 # Execute the user code
3262 # Execute the user code
3254 interactivity = "none" if silent else self.ast_node_interactivity
3263 interactivity = "none" if silent else self.ast_node_interactivity
3255
3264
3256
3265
3257 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3266 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3258 interactivity=interactivity, compiler=compiler, result=result)
3267 interactivity=interactivity, compiler=compiler, result=result)
3259
3268
3260 self.last_execution_succeeded = not has_raised
3269 self.last_execution_succeeded = not has_raised
3261 self.last_execution_result = result
3270 self.last_execution_result = result
3262
3271
3263 # Reset this so later displayed values do not modify the
3272 # Reset this so later displayed values do not modify the
3264 # ExecutionResult
3273 # ExecutionResult
3265 self.displayhook.exec_result = None
3274 self.displayhook.exec_result = None
3266
3275
3267 if store_history:
3276 if store_history:
3268 # Write output to the database. Does nothing unless
3277 # Write output to the database. Does nothing unless
3269 # history output logging is enabled.
3278 # history output logging is enabled.
3270 self.history_manager.store_output(self.execution_count)
3279 self.history_manager.store_output(self.execution_count)
3271 # Each cell is a *single* input, regardless of how many lines it has
3280 # Each cell is a *single* input, regardless of how many lines it has
3272 self.execution_count += 1
3281 self.execution_count += 1
3273
3282
3274 return result
3283 return result
3275
3284
3276 def transform_cell(self, raw_cell):
3285 def transform_cell(self, raw_cell):
3277 """Transform an input cell before parsing it.
3286 """Transform an input cell before parsing it.
3278
3287
3279 Static transformations, implemented in IPython.core.inputtransformer2,
3288 Static transformations, implemented in IPython.core.inputtransformer2,
3280 deal with things like ``%magic`` and ``!system`` commands.
3289 deal with things like ``%magic`` and ``!system`` commands.
3281 These run on all input.
3290 These run on all input.
3282 Dynamic transformations, for things like unescaped magics and the exit
3291 Dynamic transformations, for things like unescaped magics and the exit
3283 autocall, depend on the state of the interpreter.
3292 autocall, depend on the state of the interpreter.
3284 These only apply to single line inputs.
3293 These only apply to single line inputs.
3285
3294
3286 These string-based transformations are followed by AST transformations;
3295 These string-based transformations are followed by AST transformations;
3287 see :meth:`transform_ast`.
3296 see :meth:`transform_ast`.
3288 """
3297 """
3289 # Static input transformations
3298 # Static input transformations
3290 cell = self.input_transformer_manager.transform_cell(raw_cell)
3299 cell = self.input_transformer_manager.transform_cell(raw_cell)
3291
3300
3292 if len(cell.splitlines()) == 1:
3301 if len(cell.splitlines()) == 1:
3293 # Dynamic transformations - only applied for single line commands
3302 # Dynamic transformations - only applied for single line commands
3294 with self.builtin_trap:
3303 with self.builtin_trap:
3295 # use prefilter_lines to handle trailing newlines
3304 # use prefilter_lines to handle trailing newlines
3296 # restore trailing newline for ast.parse
3305 # restore trailing newline for ast.parse
3297 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3306 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3298
3307
3299 lines = cell.splitlines(keepends=True)
3308 lines = cell.splitlines(keepends=True)
3300 for transform in self.input_transformers_post:
3309 for transform in self.input_transformers_post:
3301 lines = transform(lines)
3310 lines = transform(lines)
3302 cell = ''.join(lines)
3311 cell = ''.join(lines)
3303
3312
3304 return cell
3313 return cell
3305
3314
3306 def transform_ast(self, node):
3315 def transform_ast(self, node):
3307 """Apply the AST transformations from self.ast_transformers
3316 """Apply the AST transformations from self.ast_transformers
3308
3317
3309 Parameters
3318 Parameters
3310 ----------
3319 ----------
3311 node : ast.Node
3320 node : ast.Node
3312 The root node to be transformed. Typically called with the ast.Module
3321 The root node to be transformed. Typically called with the ast.Module
3313 produced by parsing user input.
3322 produced by parsing user input.
3314
3323
3315 Returns
3324 Returns
3316 -------
3325 -------
3317 An ast.Node corresponding to the node it was called with. Note that it
3326 An ast.Node corresponding to the node it was called with. Note that it
3318 may also modify the passed object, so don't rely on references to the
3327 may also modify the passed object, so don't rely on references to the
3319 original AST.
3328 original AST.
3320 """
3329 """
3321 for transformer in self.ast_transformers:
3330 for transformer in self.ast_transformers:
3322 try:
3331 try:
3323 node = transformer.visit(node)
3332 node = transformer.visit(node)
3324 except InputRejected:
3333 except InputRejected:
3325 # User-supplied AST transformers can reject an input by raising
3334 # User-supplied AST transformers can reject an input by raising
3326 # an InputRejected. Short-circuit in this case so that we
3335 # an InputRejected. Short-circuit in this case so that we
3327 # don't unregister the transform.
3336 # don't unregister the transform.
3328 raise
3337 raise
3329 except Exception:
3338 except Exception:
3330 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3339 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3331 self.ast_transformers.remove(transformer)
3340 self.ast_transformers.remove(transformer)
3332
3341
3333 if self.ast_transformers:
3342 if self.ast_transformers:
3334 ast.fix_missing_locations(node)
3343 ast.fix_missing_locations(node)
3335 return node
3344 return node
3336
3345
3337 async def run_ast_nodes(
3346 async def run_ast_nodes(
3338 self,
3347 self,
3339 nodelist: ListType[stmt],
3348 nodelist: ListType[stmt],
3340 cell_name: str,
3349 cell_name: str,
3341 interactivity="last_expr",
3350 interactivity="last_expr",
3342 compiler=compile,
3351 compiler=compile,
3343 result=None,
3352 result=None,
3344 ):
3353 ):
3345 """Run a sequence of AST nodes. The execution mode depends on the
3354 """Run a sequence of AST nodes. The execution mode depends on the
3346 interactivity parameter.
3355 interactivity parameter.
3347
3356
3348 Parameters
3357 Parameters
3349 ----------
3358 ----------
3350 nodelist : list
3359 nodelist : list
3351 A sequence of AST nodes to run.
3360 A sequence of AST nodes to run.
3352 cell_name : str
3361 cell_name : str
3353 Will be passed to the compiler as the filename of the cell. Typically
3362 Will be passed to the compiler as the filename of the cell. Typically
3354 the value returned by ip.compile.cache(cell).
3363 the value returned by ip.compile.cache(cell).
3355 interactivity : str
3364 interactivity : str
3356 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3365 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3357 specifying which nodes should be run interactively (displaying output
3366 specifying which nodes should be run interactively (displaying output
3358 from expressions). 'last_expr' will run the last node interactively
3367 from expressions). 'last_expr' will run the last node interactively
3359 only if it is an expression (i.e. expressions in loops or other blocks
3368 only if it is an expression (i.e. expressions in loops or other blocks
3360 are not displayed) 'last_expr_or_assign' will run the last expression
3369 are not displayed) 'last_expr_or_assign' will run the last expression
3361 or the last assignment. Other values for this parameter will raise a
3370 or the last assignment. Other values for this parameter will raise a
3362 ValueError.
3371 ValueError.
3363
3372
3364 compiler : callable
3373 compiler : callable
3365 A function with the same interface as the built-in compile(), to turn
3374 A function with the same interface as the built-in compile(), to turn
3366 the AST nodes into code objects. Default is the built-in compile().
3375 the AST nodes into code objects. Default is the built-in compile().
3367 result : ExecutionResult, optional
3376 result : ExecutionResult, optional
3368 An object to store exceptions that occur during execution.
3377 An object to store exceptions that occur during execution.
3369
3378
3370 Returns
3379 Returns
3371 -------
3380 -------
3372 True if an exception occurred while running code, False if it finished
3381 True if an exception occurred while running code, False if it finished
3373 running.
3382 running.
3374 """
3383 """
3375 if not nodelist:
3384 if not nodelist:
3376 return
3385 return
3377
3386
3378
3387
3379 if interactivity == 'last_expr_or_assign':
3388 if interactivity == 'last_expr_or_assign':
3380 if isinstance(nodelist[-1], _assign_nodes):
3389 if isinstance(nodelist[-1], _assign_nodes):
3381 asg = nodelist[-1]
3390 asg = nodelist[-1]
3382 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3391 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3383 target = asg.targets[0]
3392 target = asg.targets[0]
3384 elif isinstance(asg, _single_targets_nodes):
3393 elif isinstance(asg, _single_targets_nodes):
3385 target = asg.target
3394 target = asg.target
3386 else:
3395 else:
3387 target = None
3396 target = None
3388 if isinstance(target, ast.Name):
3397 if isinstance(target, ast.Name):
3389 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3398 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3390 ast.fix_missing_locations(nnode)
3399 ast.fix_missing_locations(nnode)
3391 nodelist.append(nnode)
3400 nodelist.append(nnode)
3392 interactivity = 'last_expr'
3401 interactivity = 'last_expr'
3393
3402
3394 _async = False
3403 _async = False
3395 if interactivity == 'last_expr':
3404 if interactivity == 'last_expr':
3396 if isinstance(nodelist[-1], ast.Expr):
3405 if isinstance(nodelist[-1], ast.Expr):
3397 interactivity = "last"
3406 interactivity = "last"
3398 else:
3407 else:
3399 interactivity = "none"
3408 interactivity = "none"
3400
3409
3401 if interactivity == 'none':
3410 if interactivity == 'none':
3402 to_run_exec, to_run_interactive = nodelist, []
3411 to_run_exec, to_run_interactive = nodelist, []
3403 elif interactivity == 'last':
3412 elif interactivity == 'last':
3404 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3413 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3405 elif interactivity == 'all':
3414 elif interactivity == 'all':
3406 to_run_exec, to_run_interactive = [], nodelist
3415 to_run_exec, to_run_interactive = [], nodelist
3407 else:
3416 else:
3408 raise ValueError("Interactivity was %r" % interactivity)
3417 raise ValueError("Interactivity was %r" % interactivity)
3409
3418
3410 try:
3419 try:
3411
3420
3412 def compare(code):
3421 def compare(code):
3413 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3422 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3414 return is_async
3423 return is_async
3415
3424
3416 # refactor that to just change the mod constructor.
3425 # refactor that to just change the mod constructor.
3417 to_run = []
3426 to_run = []
3418 for node in to_run_exec:
3427 for node in to_run_exec:
3419 to_run.append((node, "exec"))
3428 to_run.append((node, "exec"))
3420
3429
3421 for node in to_run_interactive:
3430 for node in to_run_interactive:
3422 to_run.append((node, "single"))
3431 to_run.append((node, "single"))
3423
3432
3424 for node, mode in to_run:
3433 for node, mode in to_run:
3425 if mode == "exec":
3434 if mode == "exec":
3426 mod = Module([node], [])
3435 mod = Module([node], [])
3427 elif mode == "single":
3436 elif mode == "single":
3428 mod = ast.Interactive([node]) # type: ignore
3437 mod = ast.Interactive([node]) # type: ignore
3429 with compiler.extra_flags(
3438 with compiler.extra_flags(
3430 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3439 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3431 if self.autoawait
3440 if self.autoawait
3432 else 0x0
3441 else 0x0
3433 ):
3442 ):
3434 code = compiler(mod, cell_name, mode)
3443 code = compiler(mod, cell_name, mode)
3435 asy = compare(code)
3444 asy = compare(code)
3436 if await self.run_code(code, result, async_=asy):
3445 if await self.run_code(code, result, async_=asy):
3437 return True
3446 return True
3438
3447
3439 # Flush softspace
3448 # Flush softspace
3440 if softspace(sys.stdout, 0):
3449 if softspace(sys.stdout, 0):
3441 print()
3450 print()
3442
3451
3443 except:
3452 except:
3444 # It's possible to have exceptions raised here, typically by
3453 # It's possible to have exceptions raised here, typically by
3445 # compilation of odd code (such as a naked 'return' outside a
3454 # compilation of odd code (such as a naked 'return' outside a
3446 # function) that did parse but isn't valid. Typically the exception
3455 # function) that did parse but isn't valid. Typically the exception
3447 # is a SyntaxError, but it's safest just to catch anything and show
3456 # is a SyntaxError, but it's safest just to catch anything and show
3448 # the user a traceback.
3457 # the user a traceback.
3449
3458
3450 # We do only one try/except outside the loop to minimize the impact
3459 # We do only one try/except outside the loop to minimize the impact
3451 # on runtime, and also because if any node in the node list is
3460 # on runtime, and also because if any node in the node list is
3452 # broken, we should stop execution completely.
3461 # broken, we should stop execution completely.
3453 if result:
3462 if result:
3454 result.error_before_exec = sys.exc_info()[1]
3463 result.error_before_exec = sys.exc_info()[1]
3455 self.showtraceback()
3464 self.showtraceback()
3456 return True
3465 return True
3457
3466
3458 return False
3467 return False
3459
3468
3460 async def run_code(self, code_obj, result=None, *, async_=False):
3469 async def run_code(self, code_obj, result=None, *, async_=False):
3461 """Execute a code object.
3470 """Execute a code object.
3462
3471
3463 When an exception occurs, self.showtraceback() is called to display a
3472 When an exception occurs, self.showtraceback() is called to display a
3464 traceback.
3473 traceback.
3465
3474
3466 Parameters
3475 Parameters
3467 ----------
3476 ----------
3468 code_obj : code object
3477 code_obj : code object
3469 A compiled code object, to be executed
3478 A compiled code object, to be executed
3470 result : ExecutionResult, optional
3479 result : ExecutionResult, optional
3471 An object to store exceptions that occur during execution.
3480 An object to store exceptions that occur during execution.
3472 async_ : Bool (Experimental)
3481 async_ : Bool (Experimental)
3473 Attempt to run top-level asynchronous code in a default loop.
3482 Attempt to run top-level asynchronous code in a default loop.
3474
3483
3475 Returns
3484 Returns
3476 -------
3485 -------
3477 False : successful execution.
3486 False : successful execution.
3478 True : an error occurred.
3487 True : an error occurred.
3479 """
3488 """
3480 # special value to say that anything above is IPython and should be
3489 # special value to say that anything above is IPython and should be
3481 # hidden.
3490 # hidden.
3482 __tracebackhide__ = "__ipython_bottom__"
3491 __tracebackhide__ = "__ipython_bottom__"
3483 # Set our own excepthook in case the user code tries to call it
3492 # Set our own excepthook in case the user code tries to call it
3484 # directly, so that the IPython crash handler doesn't get triggered
3493 # directly, so that the IPython crash handler doesn't get triggered
3485 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3494 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3486
3495
3487 # we save the original sys.excepthook in the instance, in case config
3496 # we save the original sys.excepthook in the instance, in case config
3488 # code (such as magics) needs access to it.
3497 # code (such as magics) needs access to it.
3489 self.sys_excepthook = old_excepthook
3498 self.sys_excepthook = old_excepthook
3490 outflag = True # happens in more places, so it's easier as default
3499 outflag = True # happens in more places, so it's easier as default
3491 try:
3500 try:
3492 try:
3501 try:
3493 if async_:
3502 if async_:
3494 await eval(code_obj, self.user_global_ns, self.user_ns)
3503 await eval(code_obj, self.user_global_ns, self.user_ns)
3495 else:
3504 else:
3496 exec(code_obj, self.user_global_ns, self.user_ns)
3505 exec(code_obj, self.user_global_ns, self.user_ns)
3497 finally:
3506 finally:
3498 # Reset our crash handler in place
3507 # Reset our crash handler in place
3499 sys.excepthook = old_excepthook
3508 sys.excepthook = old_excepthook
3500 except SystemExit as e:
3509 except SystemExit as e:
3501 if result is not None:
3510 if result is not None:
3502 result.error_in_exec = e
3511 result.error_in_exec = e
3503 self.showtraceback(exception_only=True)
3512 self.showtraceback(exception_only=True)
3504 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3513 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3505 except bdb.BdbQuit:
3514 except bdb.BdbQuit:
3506 etype, value, tb = sys.exc_info()
3515 etype, value, tb = sys.exc_info()
3507 if result is not None:
3516 if result is not None:
3508 result.error_in_exec = value
3517 result.error_in_exec = value
3509 # the BdbQuit stops here
3518 # the BdbQuit stops here
3510 except self.custom_exceptions:
3519 except self.custom_exceptions:
3511 etype, value, tb = sys.exc_info()
3520 etype, value, tb = sys.exc_info()
3512 if result is not None:
3521 if result is not None:
3513 result.error_in_exec = value
3522 result.error_in_exec = value
3514 self.CustomTB(etype, value, tb)
3523 self.CustomTB(etype, value, tb)
3515 except:
3524 except:
3516 if result is not None:
3525 if result is not None:
3517 result.error_in_exec = sys.exc_info()[1]
3526 result.error_in_exec = sys.exc_info()[1]
3518 self.showtraceback(running_compiled_code=True)
3527 self.showtraceback(running_compiled_code=True)
3519 else:
3528 else:
3520 outflag = False
3529 outflag = False
3521 return outflag
3530 return outflag
3522
3531
3523 # For backwards compatibility
3532 # For backwards compatibility
3524 runcode = run_code
3533 runcode = run_code
3525
3534
3526 def check_complete(self, code: str) -> Tuple[str, str]:
3535 def check_complete(self, code: str) -> Tuple[str, str]:
3527 """Return whether a block of code is ready to execute, or should be continued
3536 """Return whether a block of code is ready to execute, or should be continued
3528
3537
3529 Parameters
3538 Parameters
3530 ----------
3539 ----------
3531 code : string
3540 code : string
3532 Python input code, which can be multiline.
3541 Python input code, which can be multiline.
3533
3542
3534 Returns
3543 Returns
3535 -------
3544 -------
3536 status : str
3545 status : str
3537 One of 'complete', 'incomplete', or 'invalid' if source is not a
3546 One of 'complete', 'incomplete', or 'invalid' if source is not a
3538 prefix of valid code.
3547 prefix of valid code.
3539 indent : str
3548 indent : str
3540 When status is 'incomplete', this is some whitespace to insert on
3549 When status is 'incomplete', this is some whitespace to insert on
3541 the next line of the prompt.
3550 the next line of the prompt.
3542 """
3551 """
3543 status, nspaces = self.input_transformer_manager.check_complete(code)
3552 status, nspaces = self.input_transformer_manager.check_complete(code)
3544 return status, ' ' * (nspaces or 0)
3553 return status, ' ' * (nspaces or 0)
3545
3554
3546 #-------------------------------------------------------------------------
3555 #-------------------------------------------------------------------------
3547 # Things related to GUI support and pylab
3556 # Things related to GUI support and pylab
3548 #-------------------------------------------------------------------------
3557 #-------------------------------------------------------------------------
3549
3558
3550 active_eventloop = None
3559 active_eventloop = None
3551
3560
3552 def enable_gui(self, gui=None):
3561 def enable_gui(self, gui=None):
3553 raise NotImplementedError('Implement enable_gui in a subclass')
3562 raise NotImplementedError('Implement enable_gui in a subclass')
3554
3563
3555 def enable_matplotlib(self, gui=None):
3564 def enable_matplotlib(self, gui=None):
3556 """Enable interactive matplotlib and inline figure support.
3565 """Enable interactive matplotlib and inline figure support.
3557
3566
3558 This takes the following steps:
3567 This takes the following steps:
3559
3568
3560 1. select the appropriate eventloop and matplotlib backend
3569 1. select the appropriate eventloop and matplotlib backend
3561 2. set up matplotlib for interactive use with that backend
3570 2. set up matplotlib for interactive use with that backend
3562 3. configure formatters for inline figure display
3571 3. configure formatters for inline figure display
3563 4. enable the selected gui eventloop
3572 4. enable the selected gui eventloop
3564
3573
3565 Parameters
3574 Parameters
3566 ----------
3575 ----------
3567 gui : optional, string
3576 gui : optional, string
3568 If given, dictates the choice of matplotlib GUI backend to use
3577 If given, dictates the choice of matplotlib GUI backend to use
3569 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3578 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3570 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3579 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3571 matplotlib (as dictated by the matplotlib build-time options plus the
3580 matplotlib (as dictated by the matplotlib build-time options plus the
3572 user's matplotlibrc configuration file). Note that not all backends
3581 user's matplotlibrc configuration file). Note that not all backends
3573 make sense in all contexts, for example a terminal ipython can't
3582 make sense in all contexts, for example a terminal ipython can't
3574 display figures inline.
3583 display figures inline.
3575 """
3584 """
3576 from matplotlib_inline.backend_inline import configure_inline_support
3585 from matplotlib_inline.backend_inline import configure_inline_support
3577
3586
3578 from IPython.core import pylabtools as pt
3587 from IPython.core import pylabtools as pt
3579 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3588 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3580
3589
3581 if gui != 'inline':
3590 if gui != 'inline':
3582 # If we have our first gui selection, store it
3591 # If we have our first gui selection, store it
3583 if self.pylab_gui_select is None:
3592 if self.pylab_gui_select is None:
3584 self.pylab_gui_select = gui
3593 self.pylab_gui_select = gui
3585 # Otherwise if they are different
3594 # Otherwise if they are different
3586 elif gui != self.pylab_gui_select:
3595 elif gui != self.pylab_gui_select:
3587 print('Warning: Cannot change to a different GUI toolkit: %s.'
3596 print('Warning: Cannot change to a different GUI toolkit: %s.'
3588 ' Using %s instead.' % (gui, self.pylab_gui_select))
3597 ' Using %s instead.' % (gui, self.pylab_gui_select))
3589 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3598 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3590
3599
3591 pt.activate_matplotlib(backend)
3600 pt.activate_matplotlib(backend)
3592 configure_inline_support(self, backend)
3601 configure_inline_support(self, backend)
3593
3602
3594 # Now we must activate the gui pylab wants to use, and fix %run to take
3603 # Now we must activate the gui pylab wants to use, and fix %run to take
3595 # plot updates into account
3604 # plot updates into account
3596 self.enable_gui(gui)
3605 self.enable_gui(gui)
3597 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3606 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3598 pt.mpl_runner(self.safe_execfile)
3607 pt.mpl_runner(self.safe_execfile)
3599
3608
3600 return gui, backend
3609 return gui, backend
3601
3610
3602 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3611 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3603 """Activate pylab support at runtime.
3612 """Activate pylab support at runtime.
3604
3613
3605 This turns on support for matplotlib, preloads into the interactive
3614 This turns on support for matplotlib, preloads into the interactive
3606 namespace all of numpy and pylab, and configures IPython to correctly
3615 namespace all of numpy and pylab, and configures IPython to correctly
3607 interact with the GUI event loop. The GUI backend to be used can be
3616 interact with the GUI event loop. The GUI backend to be used can be
3608 optionally selected with the optional ``gui`` argument.
3617 optionally selected with the optional ``gui`` argument.
3609
3618
3610 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3619 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3611
3620
3612 Parameters
3621 Parameters
3613 ----------
3622 ----------
3614 gui : optional, string
3623 gui : optional, string
3615 If given, dictates the choice of matplotlib GUI backend to use
3624 If given, dictates the choice of matplotlib GUI backend to use
3616 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3625 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3617 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3626 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3618 matplotlib (as dictated by the matplotlib build-time options plus the
3627 matplotlib (as dictated by the matplotlib build-time options plus the
3619 user's matplotlibrc configuration file). Note that not all backends
3628 user's matplotlibrc configuration file). Note that not all backends
3620 make sense in all contexts, for example a terminal ipython can't
3629 make sense in all contexts, for example a terminal ipython can't
3621 display figures inline.
3630 display figures inline.
3622 import_all : optional, bool, default: True
3631 import_all : optional, bool, default: True
3623 Whether to do `from numpy import *` and `from pylab import *`
3632 Whether to do `from numpy import *` and `from pylab import *`
3624 in addition to module imports.
3633 in addition to module imports.
3625 welcome_message : deprecated
3634 welcome_message : deprecated
3626 This argument is ignored, no welcome message will be displayed.
3635 This argument is ignored, no welcome message will be displayed.
3627 """
3636 """
3628 from IPython.core.pylabtools import import_pylab
3637 from IPython.core.pylabtools import import_pylab
3629
3638
3630 gui, backend = self.enable_matplotlib(gui)
3639 gui, backend = self.enable_matplotlib(gui)
3631
3640
3632 # We want to prevent the loading of pylab to pollute the user's
3641 # We want to prevent the loading of pylab to pollute the user's
3633 # namespace as shown by the %who* magics, so we execute the activation
3642 # namespace as shown by the %who* magics, so we execute the activation
3634 # code in an empty namespace, and we update *both* user_ns and
3643 # code in an empty namespace, and we update *both* user_ns and
3635 # user_ns_hidden with this information.
3644 # user_ns_hidden with this information.
3636 ns = {}
3645 ns = {}
3637 import_pylab(ns, import_all)
3646 import_pylab(ns, import_all)
3638 # warn about clobbered names
3647 # warn about clobbered names
3639 ignored = {"__builtins__"}
3648 ignored = {"__builtins__"}
3640 both = set(ns).intersection(self.user_ns).difference(ignored)
3649 both = set(ns).intersection(self.user_ns).difference(ignored)
3641 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3650 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3642 self.user_ns.update(ns)
3651 self.user_ns.update(ns)
3643 self.user_ns_hidden.update(ns)
3652 self.user_ns_hidden.update(ns)
3644 return gui, backend, clobbered
3653 return gui, backend, clobbered
3645
3654
3646 #-------------------------------------------------------------------------
3655 #-------------------------------------------------------------------------
3647 # Utilities
3656 # Utilities
3648 #-------------------------------------------------------------------------
3657 #-------------------------------------------------------------------------
3649
3658
3650 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3659 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3651 """Expand python variables in a string.
3660 """Expand python variables in a string.
3652
3661
3653 The depth argument indicates how many frames above the caller should
3662 The depth argument indicates how many frames above the caller should
3654 be walked to look for the local namespace where to expand variables.
3663 be walked to look for the local namespace where to expand variables.
3655
3664
3656 The global namespace for expansion is always the user's interactive
3665 The global namespace for expansion is always the user's interactive
3657 namespace.
3666 namespace.
3658 """
3667 """
3659 ns = self.user_ns.copy()
3668 ns = self.user_ns.copy()
3660 try:
3669 try:
3661 frame = sys._getframe(depth+1)
3670 frame = sys._getframe(depth+1)
3662 except ValueError:
3671 except ValueError:
3663 # This is thrown if there aren't that many frames on the stack,
3672 # This is thrown if there aren't that many frames on the stack,
3664 # e.g. if a script called run_line_magic() directly.
3673 # e.g. if a script called run_line_magic() directly.
3665 pass
3674 pass
3666 else:
3675 else:
3667 ns.update(frame.f_locals)
3676 ns.update(frame.f_locals)
3668
3677
3669 try:
3678 try:
3670 # We have to use .vformat() here, because 'self' is a valid and common
3679 # We have to use .vformat() here, because 'self' is a valid and common
3671 # name, and expanding **ns for .format() would make it collide with
3680 # name, and expanding **ns for .format() would make it collide with
3672 # the 'self' argument of the method.
3681 # the 'self' argument of the method.
3673 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3682 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3674 except Exception:
3683 except Exception:
3675 # if formatter couldn't format, just let it go untransformed
3684 # if formatter couldn't format, just let it go untransformed
3676 pass
3685 pass
3677 return cmd
3686 return cmd
3678
3687
3679 def mktempfile(self, data=None, prefix='ipython_edit_'):
3688 def mktempfile(self, data=None, prefix='ipython_edit_'):
3680 """Make a new tempfile and return its filename.
3689 """Make a new tempfile and return its filename.
3681
3690
3682 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3691 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3683 but it registers the created filename internally so ipython cleans it up
3692 but it registers the created filename internally so ipython cleans it up
3684 at exit time.
3693 at exit time.
3685
3694
3686 Optional inputs:
3695 Optional inputs:
3687
3696
3688 - data(None): if data is given, it gets written out to the temp file
3697 - data(None): if data is given, it gets written out to the temp file
3689 immediately, and the file is closed again."""
3698 immediately, and the file is closed again."""
3690
3699
3691 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3700 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3692 self.tempdirs.append(dir_path)
3701 self.tempdirs.append(dir_path)
3693
3702
3694 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3703 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3695 os.close(handle) # On Windows, there can only be one open handle on a file
3704 os.close(handle) # On Windows, there can only be one open handle on a file
3696
3705
3697 file_path = Path(filename)
3706 file_path = Path(filename)
3698 self.tempfiles.append(file_path)
3707 self.tempfiles.append(file_path)
3699
3708
3700 if data:
3709 if data:
3701 file_path.write_text(data, encoding="utf-8")
3710 file_path.write_text(data, encoding="utf-8")
3702 return filename
3711 return filename
3703
3712
3704 def ask_yes_no(self, prompt, default=None, interrupt=None):
3713 def ask_yes_no(self, prompt, default=None, interrupt=None):
3705 if self.quiet:
3714 if self.quiet:
3706 return True
3715 return True
3707 return ask_yes_no(prompt,default,interrupt)
3716 return ask_yes_no(prompt,default,interrupt)
3708
3717
3709 def show_usage(self):
3718 def show_usage(self):
3710 """Show a usage message"""
3719 """Show a usage message"""
3711 page.page(IPython.core.usage.interactive_usage)
3720 page.page(IPython.core.usage.interactive_usage)
3712
3721
3713 def extract_input_lines(self, range_str, raw=False):
3722 def extract_input_lines(self, range_str, raw=False):
3714 """Return as a string a set of input history slices.
3723 """Return as a string a set of input history slices.
3715
3724
3716 Parameters
3725 Parameters
3717 ----------
3726 ----------
3718 range_str : str
3727 range_str : str
3719 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3728 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3720 since this function is for use by magic functions which get their
3729 since this function is for use by magic functions which get their
3721 arguments as strings. The number before the / is the session
3730 arguments as strings. The number before the / is the session
3722 number: ~n goes n back from the current session.
3731 number: ~n goes n back from the current session.
3723
3732
3724 If empty string is given, returns history of current session
3733 If empty string is given, returns history of current session
3725 without the last input.
3734 without the last input.
3726
3735
3727 raw : bool, optional
3736 raw : bool, optional
3728 By default, the processed input is used. If this is true, the raw
3737 By default, the processed input is used. If this is true, the raw
3729 input history is used instead.
3738 input history is used instead.
3730
3739
3731 Notes
3740 Notes
3732 -----
3741 -----
3733 Slices can be described with two notations:
3742 Slices can be described with two notations:
3734
3743
3735 * ``N:M`` -> standard python form, means including items N...(M-1).
3744 * ``N:M`` -> standard python form, means including items N...(M-1).
3736 * ``N-M`` -> include items N..M (closed endpoint).
3745 * ``N-M`` -> include items N..M (closed endpoint).
3737 """
3746 """
3738 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3747 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3739 text = "\n".join(x for _, _, x in lines)
3748 text = "\n".join(x for _, _, x in lines)
3740
3749
3741 # Skip the last line, as it's probably the magic that called this
3750 # Skip the last line, as it's probably the magic that called this
3742 if not range_str:
3751 if not range_str:
3743 if "\n" not in text:
3752 if "\n" not in text:
3744 text = ""
3753 text = ""
3745 else:
3754 else:
3746 text = text[: text.rfind("\n")]
3755 text = text[: text.rfind("\n")]
3747
3756
3748 return text
3757 return text
3749
3758
3750 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3759 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3751 """Get a code string from history, file, url, or a string or macro.
3760 """Get a code string from history, file, url, or a string or macro.
3752
3761
3753 This is mainly used by magic functions.
3762 This is mainly used by magic functions.
3754
3763
3755 Parameters
3764 Parameters
3756 ----------
3765 ----------
3757 target : str
3766 target : str
3758 A string specifying code to retrieve. This will be tried respectively
3767 A string specifying code to retrieve. This will be tried respectively
3759 as: ranges of input history (see %history for syntax), url,
3768 as: ranges of input history (see %history for syntax), url,
3760 corresponding .py file, filename, or an expression evaluating to a
3769 corresponding .py file, filename, or an expression evaluating to a
3761 string or Macro in the user namespace.
3770 string or Macro in the user namespace.
3762
3771
3763 If empty string is given, returns complete history of current
3772 If empty string is given, returns complete history of current
3764 session, without the last line.
3773 session, without the last line.
3765
3774
3766 raw : bool
3775 raw : bool
3767 If true (default), retrieve raw history. Has no effect on the other
3776 If true (default), retrieve raw history. Has no effect on the other
3768 retrieval mechanisms.
3777 retrieval mechanisms.
3769
3778
3770 py_only : bool (default False)
3779 py_only : bool (default False)
3771 Only try to fetch python code, do not try alternative methods to decode file
3780 Only try to fetch python code, do not try alternative methods to decode file
3772 if unicode fails.
3781 if unicode fails.
3773
3782
3774 Returns
3783 Returns
3775 -------
3784 -------
3776 A string of code.
3785 A string of code.
3777 ValueError is raised if nothing is found, and TypeError if it evaluates
3786 ValueError is raised if nothing is found, and TypeError if it evaluates
3778 to an object of another type. In each case, .args[0] is a printable
3787 to an object of another type. In each case, .args[0] is a printable
3779 message.
3788 message.
3780 """
3789 """
3781 code = self.extract_input_lines(target, raw=raw) # Grab history
3790 code = self.extract_input_lines(target, raw=raw) # Grab history
3782 if code:
3791 if code:
3783 return code
3792 return code
3784 try:
3793 try:
3785 if target.startswith(('http://', 'https://')):
3794 if target.startswith(('http://', 'https://')):
3786 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3795 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3787 except UnicodeDecodeError as e:
3796 except UnicodeDecodeError as e:
3788 if not py_only :
3797 if not py_only :
3789 # Deferred import
3798 # Deferred import
3790 from urllib.request import urlopen
3799 from urllib.request import urlopen
3791 response = urlopen(target)
3800 response = urlopen(target)
3792 return response.read().decode('latin1')
3801 return response.read().decode('latin1')
3793 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3802 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3794
3803
3795 potential_target = [target]
3804 potential_target = [target]
3796 try :
3805 try :
3797 potential_target.insert(0,get_py_filename(target))
3806 potential_target.insert(0,get_py_filename(target))
3798 except IOError:
3807 except IOError:
3799 pass
3808 pass
3800
3809
3801 for tgt in potential_target :
3810 for tgt in potential_target :
3802 if os.path.isfile(tgt): # Read file
3811 if os.path.isfile(tgt): # Read file
3803 try :
3812 try :
3804 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3813 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3805 except UnicodeDecodeError as e:
3814 except UnicodeDecodeError as e:
3806 if not py_only :
3815 if not py_only :
3807 with io_open(tgt,'r', encoding='latin1') as f :
3816 with io_open(tgt,'r', encoding='latin1') as f :
3808 return f.read()
3817 return f.read()
3809 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3818 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3810 elif os.path.isdir(os.path.expanduser(tgt)):
3819 elif os.path.isdir(os.path.expanduser(tgt)):
3811 raise ValueError("'%s' is a directory, not a regular file." % target)
3820 raise ValueError("'%s' is a directory, not a regular file." % target)
3812
3821
3813 if search_ns:
3822 if search_ns:
3814 # Inspect namespace to load object source
3823 # Inspect namespace to load object source
3815 object_info = self.object_inspect(target, detail_level=1)
3824 object_info = self.object_inspect(target, detail_level=1)
3816 if object_info['found'] and object_info['source']:
3825 if object_info['found'] and object_info['source']:
3817 return object_info['source']
3826 return object_info['source']
3818
3827
3819 try: # User namespace
3828 try: # User namespace
3820 codeobj = eval(target, self.user_ns)
3829 codeobj = eval(target, self.user_ns)
3821 except Exception as e:
3830 except Exception as e:
3822 raise ValueError(("'%s' was not found in history, as a file, url, "
3831 raise ValueError(("'%s' was not found in history, as a file, url, "
3823 "nor in the user namespace.") % target) from e
3832 "nor in the user namespace.") % target) from e
3824
3833
3825 if isinstance(codeobj, str):
3834 if isinstance(codeobj, str):
3826 return codeobj
3835 return codeobj
3827 elif isinstance(codeobj, Macro):
3836 elif isinstance(codeobj, Macro):
3828 return codeobj.value
3837 return codeobj.value
3829
3838
3830 raise TypeError("%s is neither a string nor a macro." % target,
3839 raise TypeError("%s is neither a string nor a macro." % target,
3831 codeobj)
3840 codeobj)
3832
3841
3833 def _atexit_once(self):
3842 def _atexit_once(self):
3834 """
3843 """
3835 At exist operation that need to be called at most once.
3844 At exist operation that need to be called at most once.
3836 Second call to this function per instance will do nothing.
3845 Second call to this function per instance will do nothing.
3837 """
3846 """
3838
3847
3839 if not getattr(self, "_atexit_once_called", False):
3848 if not getattr(self, "_atexit_once_called", False):
3840 self._atexit_once_called = True
3849 self._atexit_once_called = True
3841 # Clear all user namespaces to release all references cleanly.
3850 # Clear all user namespaces to release all references cleanly.
3842 self.reset(new_session=False)
3851 self.reset(new_session=False)
3843 # Close the history session (this stores the end time and line count)
3852 # Close the history session (this stores the end time and line count)
3844 # this must be *before* the tempfile cleanup, in case of temporary
3853 # this must be *before* the tempfile cleanup, in case of temporary
3845 # history db
3854 # history db
3846 self.history_manager.end_session()
3855 self.history_manager.end_session()
3847 self.history_manager = None
3856 self.history_manager = None
3848
3857
3849 #-------------------------------------------------------------------------
3858 #-------------------------------------------------------------------------
3850 # Things related to IPython exiting
3859 # Things related to IPython exiting
3851 #-------------------------------------------------------------------------
3860 #-------------------------------------------------------------------------
3852 def atexit_operations(self):
3861 def atexit_operations(self):
3853 """This will be executed at the time of exit.
3862 """This will be executed at the time of exit.
3854
3863
3855 Cleanup operations and saving of persistent data that is done
3864 Cleanup operations and saving of persistent data that is done
3856 unconditionally by IPython should be performed here.
3865 unconditionally by IPython should be performed here.
3857
3866
3858 For things that may depend on startup flags or platform specifics (such
3867 For things that may depend on startup flags or platform specifics (such
3859 as having readline or not), register a separate atexit function in the
3868 as having readline or not), register a separate atexit function in the
3860 code that has the appropriate information, rather than trying to
3869 code that has the appropriate information, rather than trying to
3861 clutter
3870 clutter
3862 """
3871 """
3863 self._atexit_once()
3872 self._atexit_once()
3864
3873
3865 # Cleanup all tempfiles and folders left around
3874 # Cleanup all tempfiles and folders left around
3866 for tfile in self.tempfiles:
3875 for tfile in self.tempfiles:
3867 try:
3876 try:
3868 tfile.unlink()
3877 tfile.unlink()
3869 self.tempfiles.remove(tfile)
3878 self.tempfiles.remove(tfile)
3870 except FileNotFoundError:
3879 except FileNotFoundError:
3871 pass
3880 pass
3872 del self.tempfiles
3881 del self.tempfiles
3873 for tdir in self.tempdirs:
3882 for tdir in self.tempdirs:
3874 try:
3883 try:
3875 tdir.rmdir()
3884 tdir.rmdir()
3876 self.tempdirs.remove(tdir)
3885 self.tempdirs.remove(tdir)
3877 except FileNotFoundError:
3886 except FileNotFoundError:
3878 pass
3887 pass
3879 del self.tempdirs
3888 del self.tempdirs
3880
3889
3881 # Restore user's cursor
3890 # Restore user's cursor
3882 if hasattr(self, "editing_mode") and self.editing_mode == "vi":
3891 if hasattr(self, "editing_mode") and self.editing_mode == "vi":
3883 sys.stdout.write("\x1b[0 q")
3892 sys.stdout.write("\x1b[0 q")
3884 sys.stdout.flush()
3893 sys.stdout.flush()
3885
3894
3886 def cleanup(self):
3895 def cleanup(self):
3887 self.restore_sys_module_state()
3896 self.restore_sys_module_state()
3888
3897
3889
3898
3890 # Overridden in terminal subclass to change prompts
3899 # Overridden in terminal subclass to change prompts
3891 def switch_doctest_mode(self, mode):
3900 def switch_doctest_mode(self, mode):
3892 pass
3901 pass
3893
3902
3894
3903
3895 class InteractiveShellABC(metaclass=abc.ABCMeta):
3904 class InteractiveShellABC(metaclass=abc.ABCMeta):
3896 """An abstract base class for InteractiveShell."""
3905 """An abstract base class for InteractiveShell."""
3897
3906
3898 InteractiveShellABC.register(InteractiveShell)
3907 InteractiveShellABC.register(InteractiveShell)
@@ -1,1098 +1,1154 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12
12
13 __all__ = ['Inspector','InspectColors']
13 __all__ = ['Inspector','InspectColors']
14
14
15 # stdlib modules
15 # stdlib modules
16 import ast
16 from dataclasses import dataclass
17 import inspect
18 from inspect import signature
17 from inspect import signature
18 from textwrap import dedent
19 import ast
19 import html
20 import html
21 import inspect
22 import io as stdlib_io
20 import linecache
23 import linecache
21 import warnings
22 import os
24 import os
23 from textwrap import dedent
25 import sys
24 import types
26 import types
25 import io as stdlib_io
27 import warnings
26
28
27 from typing import Union
29 from typing import Any, Optional, Dict, Union, List, Tuple
30
31 if sys.version_info <= (3, 10):
32 from typing_extensions import TypeAlias
33 else:
34 from typing import TypeAlias
28
35
29 # IPython's own
36 # IPython's own
30 from IPython.core import page
37 from IPython.core import page
31 from IPython.lib.pretty import pretty
38 from IPython.lib.pretty import pretty
32 from IPython.testing.skipdoctest import skip_doctest
39 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.utils import PyColorize
40 from IPython.utils import PyColorize
34 from IPython.utils import openpy
41 from IPython.utils import openpy
35 from IPython.utils.dir2 import safe_hasattr
42 from IPython.utils.dir2 import safe_hasattr
36 from IPython.utils.path import compress_user
43 from IPython.utils.path import compress_user
37 from IPython.utils.text import indent
44 from IPython.utils.text import indent
38 from IPython.utils.wildcard import list_namespace
45 from IPython.utils.wildcard import list_namespace
39 from IPython.utils.wildcard import typestr2type
46 from IPython.utils.wildcard import typestr2type
40 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
47 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
41 from IPython.utils.py3compat import cast_unicode
48 from IPython.utils.py3compat import cast_unicode
42 from IPython.utils.colorable import Colorable
49 from IPython.utils.colorable import Colorable
43 from IPython.utils.decorators import undoc
50 from IPython.utils.decorators import undoc
44
51
45 from pygments import highlight
52 from pygments import highlight
46 from pygments.lexers import PythonLexer
53 from pygments.lexers import PythonLexer
47 from pygments.formatters import HtmlFormatter
54 from pygments.formatters import HtmlFormatter
48
55
49 from typing import Any, Optional
56 HOOK_NAME = "__custom_documentations__"
50 from dataclasses import dataclass
57
58
59 UnformattedBundle: TypeAlias = Dict[str, List[Tuple[str, str]]] # List of (title, body)
60 Bundle: TypeAlias = Dict[str, str]
51
61
52
62
53 @dataclass
63 @dataclass
54 class OInfo:
64 class OInfo:
55 ismagic: bool
65 ismagic: bool
56 isalias: bool
66 isalias: bool
57 found: bool
67 found: bool
58 namespace: Optional[str]
68 namespace: Optional[str]
59 parent: Any
69 parent: Any
60 obj: Any
70 obj: Any
61
71
62 def pylight(code):
72 def pylight(code):
63 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
73 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
64
74
65 # builtin docstrings to ignore
75 # builtin docstrings to ignore
66 _func_call_docstring = types.FunctionType.__call__.__doc__
76 _func_call_docstring = types.FunctionType.__call__.__doc__
67 _object_init_docstring = object.__init__.__doc__
77 _object_init_docstring = object.__init__.__doc__
68 _builtin_type_docstrings = {
78 _builtin_type_docstrings = {
69 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
79 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
70 types.FunctionType, property)
80 types.FunctionType, property)
71 }
81 }
72
82
73 _builtin_func_type = type(all)
83 _builtin_func_type = type(all)
74 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
84 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
75 #****************************************************************************
85 #****************************************************************************
76 # Builtin color schemes
86 # Builtin color schemes
77
87
78 Colors = TermColors # just a shorthand
88 Colors = TermColors # just a shorthand
79
89
80 InspectColors = PyColorize.ANSICodeColors
90 InspectColors = PyColorize.ANSICodeColors
81
91
82 #****************************************************************************
92 #****************************************************************************
83 # Auxiliary functions and objects
93 # Auxiliary functions and objects
84
94
85 # See the messaging spec for the definition of all these fields. This list
95 # See the messaging spec for the definition of all these fields. This list
86 # effectively defines the order of display
96 # effectively defines the order of display
87 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
97 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
88 'length', 'file', 'definition', 'docstring', 'source',
98 'length', 'file', 'definition', 'docstring', 'source',
89 'init_definition', 'class_docstring', 'init_docstring',
99 'init_definition', 'class_docstring', 'init_docstring',
90 'call_def', 'call_docstring',
100 'call_def', 'call_docstring',
91 # These won't be printed but will be used to determine how to
101 # These won't be printed but will be used to determine how to
92 # format the object
102 # format the object
93 'ismagic', 'isalias', 'isclass', 'found', 'name'
103 'ismagic', 'isalias', 'isclass', 'found', 'name'
94 ]
104 ]
95
105
96
106
97 def object_info(**kw):
107 def object_info(**kw):
98 """Make an object info dict with all fields present."""
108 """Make an object info dict with all fields present."""
99 infodict = {k:None for k in info_fields}
109 infodict = {k:None for k in info_fields}
100 infodict.update(kw)
110 infodict.update(kw)
101 return infodict
111 return infodict
102
112
103
113
104 def get_encoding(obj):
114 def get_encoding(obj):
105 """Get encoding for python source file defining obj
115 """Get encoding for python source file defining obj
106
116
107 Returns None if obj is not defined in a sourcefile.
117 Returns None if obj is not defined in a sourcefile.
108 """
118 """
109 ofile = find_file(obj)
119 ofile = find_file(obj)
110 # run contents of file through pager starting at line where the object
120 # run contents of file through pager starting at line where the object
111 # is defined, as long as the file isn't binary and is actually on the
121 # is defined, as long as the file isn't binary and is actually on the
112 # filesystem.
122 # filesystem.
113 if ofile is None:
123 if ofile is None:
114 return None
124 return None
115 elif ofile.endswith(('.so', '.dll', '.pyd')):
125 elif ofile.endswith(('.so', '.dll', '.pyd')):
116 return None
126 return None
117 elif not os.path.isfile(ofile):
127 elif not os.path.isfile(ofile):
118 return None
128 return None
119 else:
129 else:
120 # Print only text files, not extension binaries. Note that
130 # Print only text files, not extension binaries. Note that
121 # getsourcelines returns lineno with 1-offset and page() uses
131 # getsourcelines returns lineno with 1-offset and page() uses
122 # 0-offset, so we must adjust.
132 # 0-offset, so we must adjust.
123 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
133 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
124 encoding, lines = openpy.detect_encoding(buffer.readline)
134 encoding, lines = openpy.detect_encoding(buffer.readline)
125 return encoding
135 return encoding
126
136
127 def getdoc(obj) -> Union[str,None]:
137 def getdoc(obj) -> Union[str,None]:
128 """Stable wrapper around inspect.getdoc.
138 """Stable wrapper around inspect.getdoc.
129
139
130 This can't crash because of attribute problems.
140 This can't crash because of attribute problems.
131
141
132 It also attempts to call a getdoc() method on the given object. This
142 It also attempts to call a getdoc() method on the given object. This
133 allows objects which provide their docstrings via non-standard mechanisms
143 allows objects which provide their docstrings via non-standard mechanisms
134 (like Pyro proxies) to still be inspected by ipython's ? system.
144 (like Pyro proxies) to still be inspected by ipython's ? system.
135 """
145 """
136 # Allow objects to offer customized documentation via a getdoc method:
146 # Allow objects to offer customized documentation via a getdoc method:
137 try:
147 try:
138 ds = obj.getdoc()
148 ds = obj.getdoc()
139 except Exception:
149 except Exception:
140 pass
150 pass
141 else:
151 else:
142 if isinstance(ds, str):
152 if isinstance(ds, str):
143 return inspect.cleandoc(ds)
153 return inspect.cleandoc(ds)
144 docstr = inspect.getdoc(obj)
154 docstr = inspect.getdoc(obj)
145 return docstr
155 return docstr
146
156
147
157
148 def getsource(obj, oname='') -> Union[str,None]:
158 def getsource(obj, oname='') -> Union[str,None]:
149 """Wrapper around inspect.getsource.
159 """Wrapper around inspect.getsource.
150
160
151 This can be modified by other projects to provide customized source
161 This can be modified by other projects to provide customized source
152 extraction.
162 extraction.
153
163
154 Parameters
164 Parameters
155 ----------
165 ----------
156 obj : object
166 obj : object
157 an object whose source code we will attempt to extract
167 an object whose source code we will attempt to extract
158 oname : str
168 oname : str
159 (optional) a name under which the object is known
169 (optional) a name under which the object is known
160
170
161 Returns
171 Returns
162 -------
172 -------
163 src : unicode or None
173 src : unicode or None
164
174
165 """
175 """
166
176
167 if isinstance(obj, property):
177 if isinstance(obj, property):
168 sources = []
178 sources = []
169 for attrname in ['fget', 'fset', 'fdel']:
179 for attrname in ['fget', 'fset', 'fdel']:
170 fn = getattr(obj, attrname)
180 fn = getattr(obj, attrname)
171 if fn is not None:
181 if fn is not None:
172 encoding = get_encoding(fn)
182 encoding = get_encoding(fn)
173 oname_prefix = ('%s.' % oname) if oname else ''
183 oname_prefix = ('%s.' % oname) if oname else ''
174 sources.append(''.join(('# ', oname_prefix, attrname)))
184 sources.append(''.join(('# ', oname_prefix, attrname)))
175 if inspect.isfunction(fn):
185 if inspect.isfunction(fn):
176 _src = getsource(fn)
186 _src = getsource(fn)
177 if _src:
187 if _src:
178 # assert _src is not None, "please mypy"
188 # assert _src is not None, "please mypy"
179 sources.append(dedent(_src))
189 sources.append(dedent(_src))
180 else:
190 else:
181 # Default str/repr only prints function name,
191 # Default str/repr only prints function name,
182 # pretty.pretty prints module name too.
192 # pretty.pretty prints module name too.
183 sources.append(
193 sources.append(
184 '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
194 '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
185 )
195 )
186 if sources:
196 if sources:
187 return '\n'.join(sources)
197 return '\n'.join(sources)
188 else:
198 else:
189 return None
199 return None
190
200
191 else:
201 else:
192 # Get source for non-property objects.
202 # Get source for non-property objects.
193
203
194 obj = _get_wrapped(obj)
204 obj = _get_wrapped(obj)
195
205
196 try:
206 try:
197 src = inspect.getsource(obj)
207 src = inspect.getsource(obj)
198 except TypeError:
208 except TypeError:
199 # The object itself provided no meaningful source, try looking for
209 # The object itself provided no meaningful source, try looking for
200 # its class definition instead.
210 # its class definition instead.
201 try:
211 try:
202 src = inspect.getsource(obj.__class__)
212 src = inspect.getsource(obj.__class__)
203 except (OSError, TypeError):
213 except (OSError, TypeError):
204 return None
214 return None
205 except OSError:
215 except OSError:
206 return None
216 return None
207
217
208 return src
218 return src
209
219
210
220
211 def is_simple_callable(obj):
221 def is_simple_callable(obj):
212 """True if obj is a function ()"""
222 """True if obj is a function ()"""
213 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
223 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
214 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
224 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
215
225
216 @undoc
226 @undoc
217 def getargspec(obj):
227 def getargspec(obj):
218 """Wrapper around :func:`inspect.getfullargspec`
228 """Wrapper around :func:`inspect.getfullargspec`
219
229
220 In addition to functions and methods, this can also handle objects with a
230 In addition to functions and methods, this can also handle objects with a
221 ``__call__`` attribute.
231 ``__call__`` attribute.
222
232
223 DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
233 DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
224 """
234 """
225
235
226 warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
236 warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
227 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
237 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
228
238
229 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
239 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
230 obj = obj.__call__
240 obj = obj.__call__
231
241
232 return inspect.getfullargspec(obj)
242 return inspect.getfullargspec(obj)
233
243
234 @undoc
244 @undoc
235 def format_argspec(argspec):
245 def format_argspec(argspec):
236 """Format argspect, convenience wrapper around inspect's.
246 """Format argspect, convenience wrapper around inspect's.
237
247
238 This takes a dict instead of ordered arguments and calls
248 This takes a dict instead of ordered arguments and calls
239 inspect.format_argspec with the arguments in the necessary order.
249 inspect.format_argspec with the arguments in the necessary order.
240
250
241 DEPRECATED (since 7.10): Do not use; will be removed in future versions.
251 DEPRECATED (since 7.10): Do not use; will be removed in future versions.
242 """
252 """
243
253
244 warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
254 warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
245 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
255 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
246
256
247
257
248 return inspect.formatargspec(argspec['args'], argspec['varargs'],
258 return inspect.formatargspec(argspec['args'], argspec['varargs'],
249 argspec['varkw'], argspec['defaults'])
259 argspec['varkw'], argspec['defaults'])
250
260
251 @undoc
261 @undoc
252 def call_tip(oinfo, format_call=True):
262 def call_tip(oinfo, format_call=True):
253 """DEPRECATED since 6.0. Extract call tip data from an oinfo dict."""
263 """DEPRECATED since 6.0. Extract call tip data from an oinfo dict."""
254 warnings.warn(
264 warnings.warn(
255 "`call_tip` function is deprecated as of IPython 6.0"
265 "`call_tip` function is deprecated as of IPython 6.0"
256 "and will be removed in future versions.",
266 "and will be removed in future versions.",
257 DeprecationWarning,
267 DeprecationWarning,
258 stacklevel=2,
268 stacklevel=2,
259 )
269 )
260 # Get call definition
270 # Get call definition
261 argspec = oinfo.get('argspec')
271 argspec = oinfo.get('argspec')
262 if argspec is None:
272 if argspec is None:
263 call_line = None
273 call_line = None
264 else:
274 else:
265 # Callable objects will have 'self' as their first argument, prune
275 # Callable objects will have 'self' as their first argument, prune
266 # it out if it's there for clarity (since users do *not* pass an
276 # it out if it's there for clarity (since users do *not* pass an
267 # extra first argument explicitly).
277 # extra first argument explicitly).
268 try:
278 try:
269 has_self = argspec['args'][0] == 'self'
279 has_self = argspec['args'][0] == 'self'
270 except (KeyError, IndexError):
280 except (KeyError, IndexError):
271 pass
281 pass
272 else:
282 else:
273 if has_self:
283 if has_self:
274 argspec['args'] = argspec['args'][1:]
284 argspec['args'] = argspec['args'][1:]
275
285
276 call_line = oinfo['name']+format_argspec(argspec)
286 call_line = oinfo['name']+format_argspec(argspec)
277
287
278 # Now get docstring.
288 # Now get docstring.
279 # The priority is: call docstring, constructor docstring, main one.
289 # The priority is: call docstring, constructor docstring, main one.
280 doc = oinfo.get('call_docstring')
290 doc = oinfo.get('call_docstring')
281 if doc is None:
291 if doc is None:
282 doc = oinfo.get('init_docstring')
292 doc = oinfo.get('init_docstring')
283 if doc is None:
293 if doc is None:
284 doc = oinfo.get('docstring','')
294 doc = oinfo.get('docstring','')
285
295
286 return call_line, doc
296 return call_line, doc
287
297
288
298
289 def _get_wrapped(obj):
299 def _get_wrapped(obj):
290 """Get the original object if wrapped in one or more @decorators
300 """Get the original object if wrapped in one or more @decorators
291
301
292 Some objects automatically construct similar objects on any unrecognised
302 Some objects automatically construct similar objects on any unrecognised
293 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
303 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
294 this will arbitrarily cut off after 100 levels of obj.__wrapped__
304 this will arbitrarily cut off after 100 levels of obj.__wrapped__
295 attribute access. --TK, Jan 2016
305 attribute access. --TK, Jan 2016
296 """
306 """
297 orig_obj = obj
307 orig_obj = obj
298 i = 0
308 i = 0
299 while safe_hasattr(obj, '__wrapped__'):
309 while safe_hasattr(obj, '__wrapped__'):
300 obj = obj.__wrapped__
310 obj = obj.__wrapped__
301 i += 1
311 i += 1
302 if i > 100:
312 if i > 100:
303 # __wrapped__ is probably a lie, so return the thing we started with
313 # __wrapped__ is probably a lie, so return the thing we started with
304 return orig_obj
314 return orig_obj
305 return obj
315 return obj
306
316
307 def find_file(obj) -> str:
317 def find_file(obj) -> str:
308 """Find the absolute path to the file where an object was defined.
318 """Find the absolute path to the file where an object was defined.
309
319
310 This is essentially a robust wrapper around `inspect.getabsfile`.
320 This is essentially a robust wrapper around `inspect.getabsfile`.
311
321
312 Returns None if no file can be found.
322 Returns None if no file can be found.
313
323
314 Parameters
324 Parameters
315 ----------
325 ----------
316 obj : any Python object
326 obj : any Python object
317
327
318 Returns
328 Returns
319 -------
329 -------
320 fname : str
330 fname : str
321 The absolute path to the file where the object was defined.
331 The absolute path to the file where the object was defined.
322 """
332 """
323 obj = _get_wrapped(obj)
333 obj = _get_wrapped(obj)
324
334
325 fname = None
335 fname = None
326 try:
336 try:
327 fname = inspect.getabsfile(obj)
337 fname = inspect.getabsfile(obj)
328 except TypeError:
338 except TypeError:
329 # For an instance, the file that matters is where its class was
339 # For an instance, the file that matters is where its class was
330 # declared.
340 # declared.
331 try:
341 try:
332 fname = inspect.getabsfile(obj.__class__)
342 fname = inspect.getabsfile(obj.__class__)
333 except (OSError, TypeError):
343 except (OSError, TypeError):
334 # Can happen for builtins
344 # Can happen for builtins
335 pass
345 pass
336 except OSError:
346 except OSError:
337 pass
347 pass
338
348
339 return cast_unicode(fname)
349 return cast_unicode(fname)
340
350
341
351
342 def find_source_lines(obj):
352 def find_source_lines(obj):
343 """Find the line number in a file where an object was defined.
353 """Find the line number in a file where an object was defined.
344
354
345 This is essentially a robust wrapper around `inspect.getsourcelines`.
355 This is essentially a robust wrapper around `inspect.getsourcelines`.
346
356
347 Returns None if no file can be found.
357 Returns None if no file can be found.
348
358
349 Parameters
359 Parameters
350 ----------
360 ----------
351 obj : any Python object
361 obj : any Python object
352
362
353 Returns
363 Returns
354 -------
364 -------
355 lineno : int
365 lineno : int
356 The line number where the object definition starts.
366 The line number where the object definition starts.
357 """
367 """
358 obj = _get_wrapped(obj)
368 obj = _get_wrapped(obj)
359
369
360 try:
370 try:
361 lineno = inspect.getsourcelines(obj)[1]
371 lineno = inspect.getsourcelines(obj)[1]
362 except TypeError:
372 except TypeError:
363 # For instances, try the class object like getsource() does
373 # For instances, try the class object like getsource() does
364 try:
374 try:
365 lineno = inspect.getsourcelines(obj.__class__)[1]
375 lineno = inspect.getsourcelines(obj.__class__)[1]
366 except (OSError, TypeError):
376 except (OSError, TypeError):
367 return None
377 return None
368 except OSError:
378 except OSError:
369 return None
379 return None
370
380
371 return lineno
381 return lineno
372
382
373 class Inspector(Colorable):
383 class Inspector(Colorable):
374
384
375 def __init__(self, color_table=InspectColors,
385 def __init__(self, color_table=InspectColors,
376 code_color_table=PyColorize.ANSICodeColors,
386 code_color_table=PyColorize.ANSICodeColors,
377 scheme=None,
387 scheme=None,
378 str_detail_level=0,
388 str_detail_level=0,
379 parent=None, config=None):
389 parent=None, config=None):
380 super(Inspector, self).__init__(parent=parent, config=config)
390 super(Inspector, self).__init__(parent=parent, config=config)
381 self.color_table = color_table
391 self.color_table = color_table
382 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
392 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
383 self.format = self.parser.format
393 self.format = self.parser.format
384 self.str_detail_level = str_detail_level
394 self.str_detail_level = str_detail_level
385 self.set_active_scheme(scheme)
395 self.set_active_scheme(scheme)
386
396
387 def _getdef(self,obj,oname='') -> Union[str,None]:
397 def _getdef(self,obj,oname='') -> Union[str,None]:
388 """Return the call signature for any callable object.
398 """Return the call signature for any callable object.
389
399
390 If any exception is generated, None is returned instead and the
400 If any exception is generated, None is returned instead and the
391 exception is suppressed."""
401 exception is suppressed."""
392 try:
402 try:
393 return _render_signature(signature(obj), oname)
403 return _render_signature(signature(obj), oname)
394 except:
404 except:
395 return None
405 return None
396
406
397 def __head(self,h) -> str:
407 def __head(self,h) -> str:
398 """Return a header string with proper colors."""
408 """Return a header string with proper colors."""
399 return '%s%s%s' % (self.color_table.active_colors.header,h,
409 return '%s%s%s' % (self.color_table.active_colors.header,h,
400 self.color_table.active_colors.normal)
410 self.color_table.active_colors.normal)
401
411
402 def set_active_scheme(self, scheme):
412 def set_active_scheme(self, scheme):
403 if scheme is not None:
413 if scheme is not None:
404 self.color_table.set_active_scheme(scheme)
414 self.color_table.set_active_scheme(scheme)
405 self.parser.color_table.set_active_scheme(scheme)
415 self.parser.color_table.set_active_scheme(scheme)
406
416
407 def noinfo(self, msg, oname):
417 def noinfo(self, msg, oname):
408 """Generic message when no information is found."""
418 """Generic message when no information is found."""
409 print('No %s found' % msg, end=' ')
419 print('No %s found' % msg, end=' ')
410 if oname:
420 if oname:
411 print('for %s' % oname)
421 print('for %s' % oname)
412 else:
422 else:
413 print()
423 print()
414
424
415 def pdef(self, obj, oname=''):
425 def pdef(self, obj, oname=''):
416 """Print the call signature for any callable object.
426 """Print the call signature for any callable object.
417
427
418 If the object is a class, print the constructor information."""
428 If the object is a class, print the constructor information."""
419
429
420 if not callable(obj):
430 if not callable(obj):
421 print('Object is not callable.')
431 print('Object is not callable.')
422 return
432 return
423
433
424 header = ''
434 header = ''
425
435
426 if inspect.isclass(obj):
436 if inspect.isclass(obj):
427 header = self.__head('Class constructor information:\n')
437 header = self.__head('Class constructor information:\n')
428
438
429
439
430 output = self._getdef(obj,oname)
440 output = self._getdef(obj,oname)
431 if output is None:
441 if output is None:
432 self.noinfo('definition header',oname)
442 self.noinfo('definition header',oname)
433 else:
443 else:
434 print(header,self.format(output), end=' ')
444 print(header,self.format(output), end=' ')
435
445
436 # In Python 3, all classes are new-style, so they all have __init__.
446 # In Python 3, all classes are new-style, so they all have __init__.
437 @skip_doctest
447 @skip_doctest
438 def pdoc(self, obj, oname='', formatter=None):
448 def pdoc(self, obj, oname='', formatter=None):
439 """Print the docstring for any object.
449 """Print the docstring for any object.
440
450
441 Optional:
451 Optional:
442 -formatter: a function to run the docstring through for specially
452 -formatter: a function to run the docstring through for specially
443 formatted docstrings.
453 formatted docstrings.
444
454
445 Examples
455 Examples
446 --------
456 --------
447 In [1]: class NoInit:
457 In [1]: class NoInit:
448 ...: pass
458 ...: pass
449
459
450 In [2]: class NoDoc:
460 In [2]: class NoDoc:
451 ...: def __init__(self):
461 ...: def __init__(self):
452 ...: pass
462 ...: pass
453
463
454 In [3]: %pdoc NoDoc
464 In [3]: %pdoc NoDoc
455 No documentation found for NoDoc
465 No documentation found for NoDoc
456
466
457 In [4]: %pdoc NoInit
467 In [4]: %pdoc NoInit
458 No documentation found for NoInit
468 No documentation found for NoInit
459
469
460 In [5]: obj = NoInit()
470 In [5]: obj = NoInit()
461
471
462 In [6]: %pdoc obj
472 In [6]: %pdoc obj
463 No documentation found for obj
473 No documentation found for obj
464
474
465 In [5]: obj2 = NoDoc()
475 In [5]: obj2 = NoDoc()
466
476
467 In [6]: %pdoc obj2
477 In [6]: %pdoc obj2
468 No documentation found for obj2
478 No documentation found for obj2
469 """
479 """
470
480
471 head = self.__head # For convenience
481 head = self.__head # For convenience
472 lines = []
482 lines = []
473 ds = getdoc(obj)
483 ds = getdoc(obj)
474 if formatter:
484 if formatter:
475 ds = formatter(ds).get('plain/text', ds)
485 ds = formatter(ds).get('plain/text', ds)
476 if ds:
486 if ds:
477 lines.append(head("Class docstring:"))
487 lines.append(head("Class docstring:"))
478 lines.append(indent(ds))
488 lines.append(indent(ds))
479 if inspect.isclass(obj) and hasattr(obj, '__init__'):
489 if inspect.isclass(obj) and hasattr(obj, '__init__'):
480 init_ds = getdoc(obj.__init__)
490 init_ds = getdoc(obj.__init__)
481 if init_ds is not None:
491 if init_ds is not None:
482 lines.append(head("Init docstring:"))
492 lines.append(head("Init docstring:"))
483 lines.append(indent(init_ds))
493 lines.append(indent(init_ds))
484 elif hasattr(obj,'__call__'):
494 elif hasattr(obj,'__call__'):
485 call_ds = getdoc(obj.__call__)
495 call_ds = getdoc(obj.__call__)
486 if call_ds:
496 if call_ds:
487 lines.append(head("Call docstring:"))
497 lines.append(head("Call docstring:"))
488 lines.append(indent(call_ds))
498 lines.append(indent(call_ds))
489
499
490 if not lines:
500 if not lines:
491 self.noinfo('documentation',oname)
501 self.noinfo('documentation',oname)
492 else:
502 else:
493 page.page('\n'.join(lines))
503 page.page('\n'.join(lines))
494
504
495 def psource(self, obj, oname=''):
505 def psource(self, obj, oname=''):
496 """Print the source code for an object."""
506 """Print the source code for an object."""
497
507
498 # Flush the source cache because inspect can return out-of-date source
508 # Flush the source cache because inspect can return out-of-date source
499 linecache.checkcache()
509 linecache.checkcache()
500 try:
510 try:
501 src = getsource(obj, oname=oname)
511 src = getsource(obj, oname=oname)
502 except Exception:
512 except Exception:
503 src = None
513 src = None
504
514
505 if src is None:
515 if src is None:
506 self.noinfo('source', oname)
516 self.noinfo('source', oname)
507 else:
517 else:
508 page.page(self.format(src))
518 page.page(self.format(src))
509
519
510 def pfile(self, obj, oname=''):
520 def pfile(self, obj, oname=''):
511 """Show the whole file where an object was defined."""
521 """Show the whole file where an object was defined."""
512
522
513 lineno = find_source_lines(obj)
523 lineno = find_source_lines(obj)
514 if lineno is None:
524 if lineno is None:
515 self.noinfo('file', oname)
525 self.noinfo('file', oname)
516 return
526 return
517
527
518 ofile = find_file(obj)
528 ofile = find_file(obj)
519 # run contents of file through pager starting at line where the object
529 # run contents of file through pager starting at line where the object
520 # is defined, as long as the file isn't binary and is actually on the
530 # is defined, as long as the file isn't binary and is actually on the
521 # filesystem.
531 # filesystem.
522 if ofile.endswith(('.so', '.dll', '.pyd')):
532 if ofile.endswith(('.so', '.dll', '.pyd')):
523 print('File %r is binary, not printing.' % ofile)
533 print('File %r is binary, not printing.' % ofile)
524 elif not os.path.isfile(ofile):
534 elif not os.path.isfile(ofile):
525 print('File %r does not exist, not printing.' % ofile)
535 print('File %r does not exist, not printing.' % ofile)
526 else:
536 else:
527 # Print only text files, not extension binaries. Note that
537 # Print only text files, not extension binaries. Note that
528 # getsourcelines returns lineno with 1-offset and page() uses
538 # getsourcelines returns lineno with 1-offset and page() uses
529 # 0-offset, so we must adjust.
539 # 0-offset, so we must adjust.
530 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
540 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
531
541
532
542
533 def _mime_format(self, text:str, formatter=None) -> dict:
543 def _mime_format(self, text:str, formatter=None) -> dict:
534 """Return a mime bundle representation of the input text.
544 """Return a mime bundle representation of the input text.
535
545
536 - if `formatter` is None, the returned mime bundle has
546 - if `formatter` is None, the returned mime bundle has
537 a ``text/plain`` field, with the input text.
547 a ``text/plain`` field, with the input text.
538 a ``text/html`` field with a ``<pre>`` tag containing the input text.
548 a ``text/html`` field with a ``<pre>`` tag containing the input text.
539
549
540 - if ``formatter`` is not None, it must be a callable transforming the
550 - if ``formatter`` is not None, it must be a callable transforming the
541 input text into a mime bundle. Default values for ``text/plain`` and
551 input text into a mime bundle. Default values for ``text/plain`` and
542 ``text/html`` representations are the ones described above.
552 ``text/html`` representations are the ones described above.
543
553
544 Note:
554 Note:
545
555
546 Formatters returning strings are supported but this behavior is deprecated.
556 Formatters returning strings are supported but this behavior is deprecated.
547
557
548 """
558 """
549 defaults = {
559 defaults = {
550 "text/plain": text,
560 "text/plain": text,
551 "text/html": f"<pre>{html.escape(text)}</pre>",
561 "text/html": f"<pre>{html.escape(text)}</pre>",
552 }
562 }
553
563
554 if formatter is None:
564 if formatter is None:
555 return defaults
565 return defaults
556 else:
566 else:
557 formatted = formatter(text)
567 formatted = formatter(text)
558
568
559 if not isinstance(formatted, dict):
569 if not isinstance(formatted, dict):
560 # Handle the deprecated behavior of a formatter returning
570 # Handle the deprecated behavior of a formatter returning
561 # a string instead of a mime bundle.
571 # a string instead of a mime bundle.
562 return {"text/plain": formatted, "text/html": f"<pre>{formatted}</pre>"}
572 return {"text/plain": formatted, "text/html": f"<pre>{formatted}</pre>"}
563
573
564 else:
574 else:
565 return dict(defaults, **formatted)
575 return dict(defaults, **formatted)
566
576
567
577 def format_mime(self, bundle: UnformattedBundle) -> Bundle:
568 def format_mime(self, bundle):
569 """Format a mimebundle being created by _make_info_unformatted into a real mimebundle"""
578 """Format a mimebundle being created by _make_info_unformatted into a real mimebundle"""
570 # Format text/plain mimetype
579 # Format text/plain mimetype
571 if isinstance(bundle["text/plain"], (list, tuple)):
580 assert isinstance(bundle["text/plain"], list)
572 # bundle['text/plain'] is a list of (head, formatted body) pairs
581 for item in bundle["text/plain"]:
573 lines = []
582 assert isinstance(item, tuple)
574 _len = max(len(h) for h, _ in bundle["text/plain"])
575
576 for head, body in bundle["text/plain"]:
577 body = body.strip("\n")
578 delim = "\n" if "\n" in body else " "
579 lines.append(
580 f"{self.__head(head+':')}{(_len - len(head))*' '}{delim}{body}"
581 )
582
583
583 bundle["text/plain"] = "\n".join(lines)
584 new_b: Bundle = {}
585 lines = []
586 _len = max(len(h) for h, _ in bundle["text/plain"])
584
587
585 # Format the text/html mimetype
588 for head, body in bundle["text/plain"]:
586 if isinstance(bundle["text/html"], (list, tuple)):
589 body = body.strip("\n")
587 # bundle['text/html'] is a list of (head, formatted body) pairs
590 delim = "\n" if "\n" in body else " "
588 bundle["text/html"] = "\n".join(
591 lines.append(
589 (f"<h1>{head}</h1>\n{body}" for (head, body) in bundle["text/html"])
592 f"{self.__head(head+':')}{(_len - len(head))*' '}{delim}{body}"
590 )
593 )
591 return bundle
594
595 new_b["text/plain"] = "\n".join(lines)
596
597 if "text/html" in bundle:
598 assert isinstance(bundle["text/html"], list)
599 for item in bundle["text/html"]:
600 assert isinstance(item, tuple)
601 # Format the text/html mimetype
602 if isinstance(bundle["text/html"], (list, tuple)):
603 # bundle['text/html'] is a list of (head, formatted body) pairs
604 new_b["text/html"] = "\n".join(
605 (f"<h1>{head}</h1>\n{body}" for (head, body) in bundle["text/html"])
606 )
607
608 for k in bundle.keys():
609 if k in ("text/html", "text/plain"):
610 continue
611 else:
612 new_b = bundle[k] # type:ignore
613 return new_b
592
614
593 def _append_info_field(
615 def _append_info_field(
594 self, bundle, title: str, key: str, info, omit_sections, formatter
616 self,
617 bundle: UnformattedBundle,
618 title: str,
619 key: str,
620 info,
621 omit_sections,
622 formatter,
595 ):
623 ):
596 """Append an info value to the unformatted mimebundle being constructed by _make_info_unformatted"""
624 """Append an info value to the unformatted mimebundle being constructed by _make_info_unformatted"""
597 if title in omit_sections or key in omit_sections:
625 if title in omit_sections or key in omit_sections:
598 return
626 return
599 field = info[key]
627 field = info[key]
600 if field is not None:
628 if field is not None:
601 formatted_field = self._mime_format(field, formatter)
629 formatted_field = self._mime_format(field, formatter)
602 bundle["text/plain"].append((title, formatted_field["text/plain"]))
630 bundle["text/plain"].append((title, formatted_field["text/plain"]))
603 bundle["text/html"].append((title, formatted_field["text/html"]))
631 bundle["text/html"].append((title, formatted_field["text/html"]))
604
632
605 def _make_info_unformatted(self, obj, info, formatter, detail_level, omit_sections):
633 def _make_info_unformatted(
634 self, obj, info, formatter, detail_level, omit_sections
635 ) -> UnformattedBundle:
606 """Assemble the mimebundle as unformatted lists of information"""
636 """Assemble the mimebundle as unformatted lists of information"""
607 bundle = {
637 bundle: UnformattedBundle = {
608 "text/plain": [],
638 "text/plain": [],
609 "text/html": [],
639 "text/html": [],
610 }
640 }
611
641
612 # A convenience function to simplify calls below
642 # A convenience function to simplify calls below
613 def append_field(bundle, title: str, key: str, formatter=None):
643 def append_field(
644 bundle: UnformattedBundle, title: str, key: str, formatter=None
645 ):
614 self._append_info_field(
646 self._append_info_field(
615 bundle,
647 bundle,
616 title=title,
648 title=title,
617 key=key,
649 key=key,
618 info=info,
650 info=info,
619 omit_sections=omit_sections,
651 omit_sections=omit_sections,
620 formatter=formatter,
652 formatter=formatter,
621 )
653 )
622
654
623 def code_formatter(text):
655 def code_formatter(text) -> Bundle:
624 return {
656 return {
625 'text/plain': self.format(text),
657 'text/plain': self.format(text),
626 'text/html': pylight(text)
658 'text/html': pylight(text)
627 }
659 }
628
660
629 if info["isalias"]:
661 if info["isalias"]:
630 append_field(bundle, "Repr", "string_form")
662 append_field(bundle, "Repr", "string_form")
631
663
632 elif info['ismagic']:
664 elif info['ismagic']:
633 if detail_level > 0:
665 if detail_level > 0:
634 append_field(bundle, "Source", "source", code_formatter)
666 append_field(bundle, "Source", "source", code_formatter)
635 else:
667 else:
636 append_field(bundle, "Docstring", "docstring", formatter)
668 append_field(bundle, "Docstring", "docstring", formatter)
637 append_field(bundle, "File", "file")
669 append_field(bundle, "File", "file")
638
670
639 elif info['isclass'] or is_simple_callable(obj):
671 elif info['isclass'] or is_simple_callable(obj):
640 # Functions, methods, classes
672 # Functions, methods, classes
641 append_field(bundle, "Signature", "definition", code_formatter)
673 append_field(bundle, "Signature", "definition", code_formatter)
642 append_field(bundle, "Init signature", "init_definition", code_formatter)
674 append_field(bundle, "Init signature", "init_definition", code_formatter)
643 append_field(bundle, "Docstring", "docstring", formatter)
675 append_field(bundle, "Docstring", "docstring", formatter)
644 if detail_level > 0 and info["source"]:
676 if detail_level > 0 and info["source"]:
645 append_field(bundle, "Source", "source", code_formatter)
677 append_field(bundle, "Source", "source", code_formatter)
646 else:
678 else:
647 append_field(bundle, "Init docstring", "init_docstring", formatter)
679 append_field(bundle, "Init docstring", "init_docstring", formatter)
648
680
649 append_field(bundle, "File", "file")
681 append_field(bundle, "File", "file")
650 append_field(bundle, "Type", "type_name")
682 append_field(bundle, "Type", "type_name")
651 append_field(bundle, "Subclasses", "subclasses")
683 append_field(bundle, "Subclasses", "subclasses")
652
684
653 else:
685 else:
654 # General Python objects
686 # General Python objects
655 append_field(bundle, "Signature", "definition", code_formatter)
687 append_field(bundle, "Signature", "definition", code_formatter)
656 append_field(bundle, "Call signature", "call_def", code_formatter)
688 append_field(bundle, "Call signature", "call_def", code_formatter)
657 append_field(bundle, "Type", "type_name")
689 append_field(bundle, "Type", "type_name")
658 append_field(bundle, "String form", "string_form")
690 append_field(bundle, "String form", "string_form")
659
691
660 # Namespace
692 # Namespace
661 if info["namespace"] != "Interactive":
693 if info["namespace"] != "Interactive":
662 append_field(bundle, "Namespace", "namespace")
694 append_field(bundle, "Namespace", "namespace")
663
695
664 append_field(bundle, "Length", "length")
696 append_field(bundle, "Length", "length")
665 append_field(bundle, "File", "file")
697 append_field(bundle, "File", "file")
666
698
667 # Source or docstring, depending on detail level and whether
699 # Source or docstring, depending on detail level and whether
668 # source found.
700 # source found.
669 if detail_level > 0 and info["source"]:
701 if detail_level > 0 and info["source"]:
670 append_field(bundle, "Source", "source", code_formatter)
702 append_field(bundle, "Source", "source", code_formatter)
671 else:
703 else:
672 append_field(bundle, "Docstring", "docstring", formatter)
704 append_field(bundle, "Docstring", "docstring", formatter)
673
705
674 append_field(bundle, "Class docstring", "class_docstring", formatter)
706 append_field(bundle, "Class docstring", "class_docstring", formatter)
675 append_field(bundle, "Init docstring", "init_docstring", formatter)
707 append_field(bundle, "Init docstring", "init_docstring", formatter)
676 append_field(bundle, "Call docstring", "call_docstring", formatter)
708 append_field(bundle, "Call docstring", "call_docstring", formatter)
677 return bundle
709 return bundle
678
710
679
711
680 def _get_info(
712 def _get_info(
681 self, obj, oname="", formatter=None, info=None, detail_level=0, omit_sections=()
713 self,
682 ):
714 obj: Any,
715 oname: str = "",
716 formatter=None,
717 info: Optional[OInfo] = None,
718 detail_level=0,
719 omit_sections=(),
720 ) -> Bundle:
683 """Retrieve an info dict and format it.
721 """Retrieve an info dict and format it.
684
722
685 Parameters
723 Parameters
686 ----------
724 ----------
687 obj : any
725 obj : any
688 Object to inspect and return info from
726 Object to inspect and return info from
689 oname : str (default: ''):
727 oname : str (default: ''):
690 Name of the variable pointing to `obj`.
728 Name of the variable pointing to `obj`.
691 formatter : callable
729 formatter : callable
692 info
730 info
693 already computed information
731 already computed information
694 detail_level : integer
732 detail_level : integer
695 Granularity of detail level, if set to 1, give more information.
733 Granularity of detail level, if set to 1, give more information.
696 omit_sections : container[str]
734 omit_sections : container[str]
697 Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
735 Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
698 """
736 """
699
737
700 info = self.info(obj, oname=oname, info=info, detail_level=detail_level)
738 info_dict = self.info(obj, oname=oname, info=info, detail_level=detail_level)
701 bundle = self._make_info_unformatted(
739 bundle = self._make_info_unformatted(
702 obj, info, formatter, detail_level=detail_level, omit_sections=omit_sections
740 obj,
741 info_dict,
742 formatter,
743 detail_level=detail_level,
744 omit_sections=omit_sections,
703 )
745 )
704 return self.format_mime(bundle)
746 return self.format_mime(bundle)
705
747
706 def pinfo(
748 def pinfo(
707 self,
749 self,
708 obj,
750 obj,
709 oname="",
751 oname="",
710 formatter=None,
752 formatter=None,
711 info=None,
753 info: Optional[OInfo] = None,
712 detail_level=0,
754 detail_level=0,
713 enable_html_pager=True,
755 enable_html_pager=True,
714 omit_sections=(),
756 omit_sections=(),
715 ):
757 ):
716 """Show detailed information about an object.
758 """Show detailed information about an object.
717
759
718 Optional arguments:
760 Optional arguments:
719
761
720 - oname: name of the variable pointing to the object.
762 - oname: name of the variable pointing to the object.
721
763
722 - formatter: callable (optional)
764 - formatter: callable (optional)
723 A special formatter for docstrings.
765 A special formatter for docstrings.
724
766
725 The formatter is a callable that takes a string as an input
767 The formatter is a callable that takes a string as an input
726 and returns either a formatted string or a mime type bundle
768 and returns either a formatted string or a mime type bundle
727 in the form of a dictionary.
769 in the form of a dictionary.
728
770
729 Although the support of custom formatter returning a string
771 Although the support of custom formatter returning a string
730 instead of a mime type bundle is deprecated.
772 instead of a mime type bundle is deprecated.
731
773
732 - info: a structure with some information fields which may have been
774 - info: a structure with some information fields which may have been
733 precomputed already.
775 precomputed already.
734
776
735 - detail_level: if set to 1, more information is given.
777 - detail_level: if set to 1, more information is given.
736
778
737 - omit_sections: set of section keys and titles to omit
779 - omit_sections: set of section keys and titles to omit
738 """
780 """
739 info = self._get_info(
781 assert info is not None
782 info_b: Bundle = self._get_info(
740 obj, oname, formatter, info, detail_level, omit_sections=omit_sections
783 obj, oname, formatter, info, detail_level, omit_sections=omit_sections
741 )
784 )
742 if not enable_html_pager:
785 if not enable_html_pager:
743 del info['text/html']
786 del info_b["text/html"]
744 page.page(info)
787 page.page(info_b)
745
788
746 def _info(self, obj, oname="", info=None, detail_level=0):
789 def _info(self, obj, oname="", info=None, detail_level=0):
747 """
790 """
748 Inspector.info() was likely improperly marked as deprecated
791 Inspector.info() was likely improperly marked as deprecated
749 while only a parameter was deprecated. We "un-deprecate" it.
792 while only a parameter was deprecated. We "un-deprecate" it.
750 """
793 """
751
794
752 warnings.warn(
795 warnings.warn(
753 "The `Inspector.info()` method has been un-deprecated as of 8.0 "
796 "The `Inspector.info()` method has been un-deprecated as of 8.0 "
754 "and the `formatter=` keyword removed. `Inspector._info` is now "
797 "and the `formatter=` keyword removed. `Inspector._info` is now "
755 "an alias, and you can just call `.info()` directly.",
798 "an alias, and you can just call `.info()` directly.",
756 DeprecationWarning,
799 DeprecationWarning,
757 stacklevel=2,
800 stacklevel=2,
758 )
801 )
759 return self.info(obj, oname=oname, info=info, detail_level=detail_level)
802 return self.info(obj, oname=oname, info=info, detail_level=detail_level)
760
803
761 def info(self, obj, oname="", info=None, detail_level=0) -> dict:
804 def info(self, obj, oname="", info=None, detail_level=0) -> Dict[str, Any]:
762 """Compute a dict with detailed information about an object.
805 """Compute a dict with detailed information about an object.
763
806
764 Parameters
807 Parameters
765 ----------
808 ----------
766 obj : any
809 obj : any
767 An object to find information about
810 An object to find information about
768 oname : str (default: '')
811 oname : str (default: '')
769 Name of the variable pointing to `obj`.
812 Name of the variable pointing to `obj`.
770 info : (default: None)
813 info : (default: None)
771 A struct (dict like with attr access) with some information fields
814 A struct (dict like with attr access) with some information fields
772 which may have been precomputed already.
815 which may have been precomputed already.
773 detail_level : int (default:0)
816 detail_level : int (default:0)
774 If set to 1, more information is given.
817 If set to 1, more information is given.
775
818
776 Returns
819 Returns
777 -------
820 -------
778 An object info dict with known fields from `info_fields`. Keys are
821 An object info dict with known fields from `info_fields`. Keys are
779 strings, values are string or None.
822 strings, values are string or None.
780 """
823 """
781
824
782 if info is None:
825 if info is None:
783 ismagic = False
826 ismagic = False
784 isalias = False
827 isalias = False
785 ospace = ''
828 ospace = ''
786 else:
829 else:
787 ismagic = info.ismagic
830 ismagic = info.ismagic
788 isalias = info.isalias
831 isalias = info.isalias
789 ospace = info.namespace
832 ospace = info.namespace
790
833
791 # Get docstring, special-casing aliases:
834 # Get docstring, special-casing aliases:
792 if isalias:
835 att_name = oname.split(".")[-1]
836 parents_docs = None
837 prelude = ""
838 if info and info.parent and hasattr(info.parent, HOOK_NAME):
839 parents_docs_dict = getattr(info.parent, HOOK_NAME)
840 parents_docs = parents_docs_dict.get(att_name, None)
841 out = dict(
842 name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None
843 )
844
845 if parents_docs:
846 ds = parents_docs
847 elif isalias:
793 if not callable(obj):
848 if not callable(obj):
794 try:
849 try:
795 ds = "Alias to the system command:\n %s" % obj[1]
850 ds = "Alias to the system command:\n %s" % obj[1]
796 except:
851 except:
797 ds = "Alias: " + str(obj)
852 ds = "Alias: " + str(obj)
798 else:
853 else:
799 ds = "Alias to " + str(obj)
854 ds = "Alias to " + str(obj)
800 if obj.__doc__:
855 if obj.__doc__:
801 ds += "\nDocstring:\n" + obj.__doc__
856 ds += "\nDocstring:\n" + obj.__doc__
802 else:
857 else:
803 ds_or_None = getdoc(obj)
858 ds_or_None = getdoc(obj)
804 if ds_or_None is None:
859 if ds_or_None is None:
805 ds = '<no docstring>'
860 ds = '<no docstring>'
806 else:
861 else:
807 ds = ds_or_None
862 ds = ds_or_None
808
863
864 ds = prelude + ds
865
809 # store output in a dict, we initialize it here and fill it as we go
866 # store output in a dict, we initialize it here and fill it as we go
810 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
811
867
812 string_max = 200 # max size of strings to show (snipped if longer)
868 string_max = 200 # max size of strings to show (snipped if longer)
813 shalf = int((string_max - 5) / 2)
869 shalf = int((string_max - 5) / 2)
814
870
815 if ismagic:
871 if ismagic:
816 out['type_name'] = 'Magic function'
872 out['type_name'] = 'Magic function'
817 elif isalias:
873 elif isalias:
818 out['type_name'] = 'System alias'
874 out['type_name'] = 'System alias'
819 else:
875 else:
820 out['type_name'] = type(obj).__name__
876 out['type_name'] = type(obj).__name__
821
877
822 try:
878 try:
823 bclass = obj.__class__
879 bclass = obj.__class__
824 out['base_class'] = str(bclass)
880 out['base_class'] = str(bclass)
825 except:
881 except:
826 pass
882 pass
827
883
828 # String form, but snip if too long in ? form (full in ??)
884 # String form, but snip if too long in ? form (full in ??)
829 if detail_level >= self.str_detail_level:
885 if detail_level >= self.str_detail_level:
830 try:
886 try:
831 ostr = str(obj)
887 ostr = str(obj)
832 str_head = 'string_form'
888 str_head = 'string_form'
833 if not detail_level and len(ostr)>string_max:
889 if not detail_level and len(ostr)>string_max:
834 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
890 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
835 ostr = ("\n" + " " * len(str_head.expandtabs())).\
891 ostr = ("\n" + " " * len(str_head.expandtabs())).\
836 join(q.strip() for q in ostr.split("\n"))
892 join(q.strip() for q in ostr.split("\n"))
837 out[str_head] = ostr
893 out[str_head] = ostr
838 except:
894 except:
839 pass
895 pass
840
896
841 if ospace:
897 if ospace:
842 out['namespace'] = ospace
898 out['namespace'] = ospace
843
899
844 # Length (for strings and lists)
900 # Length (for strings and lists)
845 try:
901 try:
846 out['length'] = str(len(obj))
902 out['length'] = str(len(obj))
847 except Exception:
903 except Exception:
848 pass
904 pass
849
905
850 # Filename where object was defined
906 # Filename where object was defined
851 binary_file = False
907 binary_file = False
852 fname = find_file(obj)
908 fname = find_file(obj)
853 if fname is None:
909 if fname is None:
854 # if anything goes wrong, we don't want to show source, so it's as
910 # if anything goes wrong, we don't want to show source, so it's as
855 # if the file was binary
911 # if the file was binary
856 binary_file = True
912 binary_file = True
857 else:
913 else:
858 if fname.endswith(('.so', '.dll', '.pyd')):
914 if fname.endswith(('.so', '.dll', '.pyd')):
859 binary_file = True
915 binary_file = True
860 elif fname.endswith('<string>'):
916 elif fname.endswith('<string>'):
861 fname = 'Dynamically generated function. No source code available.'
917 fname = 'Dynamically generated function. No source code available.'
862 out['file'] = compress_user(fname)
918 out['file'] = compress_user(fname)
863
919
864 # Original source code for a callable, class or property.
920 # Original source code for a callable, class or property.
865 if detail_level:
921 if detail_level:
866 # Flush the source cache because inspect can return out-of-date
922 # Flush the source cache because inspect can return out-of-date
867 # source
923 # source
868 linecache.checkcache()
924 linecache.checkcache()
869 try:
925 try:
870 if isinstance(obj, property) or not binary_file:
926 if isinstance(obj, property) or not binary_file:
871 src = getsource(obj, oname)
927 src = getsource(obj, oname)
872 if src is not None:
928 if src is not None:
873 src = src.rstrip()
929 src = src.rstrip()
874 out['source'] = src
930 out['source'] = src
875
931
876 except Exception:
932 except Exception:
877 pass
933 pass
878
934
879 # Add docstring only if no source is to be shown (avoid repetitions).
935 # Add docstring only if no source is to be shown (avoid repetitions).
880 if ds and not self._source_contains_docstring(out.get('source'), ds):
936 if ds and not self._source_contains_docstring(out.get('source'), ds):
881 out['docstring'] = ds
937 out['docstring'] = ds
882
938
883 # Constructor docstring for classes
939 # Constructor docstring for classes
884 if inspect.isclass(obj):
940 if inspect.isclass(obj):
885 out['isclass'] = True
941 out['isclass'] = True
886
942
887 # get the init signature:
943 # get the init signature:
888 try:
944 try:
889 init_def = self._getdef(obj, oname)
945 init_def = self._getdef(obj, oname)
890 except AttributeError:
946 except AttributeError:
891 init_def = None
947 init_def = None
892
948
893 # get the __init__ docstring
949 # get the __init__ docstring
894 try:
950 try:
895 obj_init = obj.__init__
951 obj_init = obj.__init__
896 except AttributeError:
952 except AttributeError:
897 init_ds = None
953 init_ds = None
898 else:
954 else:
899 if init_def is None:
955 if init_def is None:
900 # Get signature from init if top-level sig failed.
956 # Get signature from init if top-level sig failed.
901 # Can happen for built-in types (list, etc.).
957 # Can happen for built-in types (list, etc.).
902 try:
958 try:
903 init_def = self._getdef(obj_init, oname)
959 init_def = self._getdef(obj_init, oname)
904 except AttributeError:
960 except AttributeError:
905 pass
961 pass
906 init_ds = getdoc(obj_init)
962 init_ds = getdoc(obj_init)
907 # Skip Python's auto-generated docstrings
963 # Skip Python's auto-generated docstrings
908 if init_ds == _object_init_docstring:
964 if init_ds == _object_init_docstring:
909 init_ds = None
965 init_ds = None
910
966
911 if init_def:
967 if init_def:
912 out['init_definition'] = init_def
968 out['init_definition'] = init_def
913
969
914 if init_ds:
970 if init_ds:
915 out['init_docstring'] = init_ds
971 out['init_docstring'] = init_ds
916
972
917 names = [sub.__name__ for sub in type.__subclasses__(obj)]
973 names = [sub.__name__ for sub in type.__subclasses__(obj)]
918 if len(names) < 10:
974 if len(names) < 10:
919 all_names = ', '.join(names)
975 all_names = ', '.join(names)
920 else:
976 else:
921 all_names = ', '.join(names[:10]+['...'])
977 all_names = ', '.join(names[:10]+['...'])
922 out['subclasses'] = all_names
978 out['subclasses'] = all_names
923 # and class docstring for instances:
979 # and class docstring for instances:
924 else:
980 else:
925 # reconstruct the function definition and print it:
981 # reconstruct the function definition and print it:
926 defln = self._getdef(obj, oname)
982 defln = self._getdef(obj, oname)
927 if defln:
983 if defln:
928 out['definition'] = defln
984 out['definition'] = defln
929
985
930 # First, check whether the instance docstring is identical to the
986 # First, check whether the instance docstring is identical to the
931 # class one, and print it separately if they don't coincide. In
987 # class one, and print it separately if they don't coincide. In
932 # most cases they will, but it's nice to print all the info for
988 # most cases they will, but it's nice to print all the info for
933 # objects which use instance-customized docstrings.
989 # objects which use instance-customized docstrings.
934 if ds:
990 if ds:
935 try:
991 try:
936 cls = getattr(obj,'__class__')
992 cls = getattr(obj,'__class__')
937 except:
993 except:
938 class_ds = None
994 class_ds = None
939 else:
995 else:
940 class_ds = getdoc(cls)
996 class_ds = getdoc(cls)
941 # Skip Python's auto-generated docstrings
997 # Skip Python's auto-generated docstrings
942 if class_ds in _builtin_type_docstrings:
998 if class_ds in _builtin_type_docstrings:
943 class_ds = None
999 class_ds = None
944 if class_ds and ds != class_ds:
1000 if class_ds and ds != class_ds:
945 out['class_docstring'] = class_ds
1001 out['class_docstring'] = class_ds
946
1002
947 # Next, try to show constructor docstrings
1003 # Next, try to show constructor docstrings
948 try:
1004 try:
949 init_ds = getdoc(obj.__init__)
1005 init_ds = getdoc(obj.__init__)
950 # Skip Python's auto-generated docstrings
1006 # Skip Python's auto-generated docstrings
951 if init_ds == _object_init_docstring:
1007 if init_ds == _object_init_docstring:
952 init_ds = None
1008 init_ds = None
953 except AttributeError:
1009 except AttributeError:
954 init_ds = None
1010 init_ds = None
955 if init_ds:
1011 if init_ds:
956 out['init_docstring'] = init_ds
1012 out['init_docstring'] = init_ds
957
1013
958 # Call form docstring for callable instances
1014 # Call form docstring for callable instances
959 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
1015 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
960 call_def = self._getdef(obj.__call__, oname)
1016 call_def = self._getdef(obj.__call__, oname)
961 if call_def and (call_def != out.get('definition')):
1017 if call_def and (call_def != out.get('definition')):
962 # it may never be the case that call def and definition differ,
1018 # it may never be the case that call def and definition differ,
963 # but don't include the same signature twice
1019 # but don't include the same signature twice
964 out['call_def'] = call_def
1020 out['call_def'] = call_def
965 call_ds = getdoc(obj.__call__)
1021 call_ds = getdoc(obj.__call__)
966 # Skip Python's auto-generated docstrings
1022 # Skip Python's auto-generated docstrings
967 if call_ds == _func_call_docstring:
1023 if call_ds == _func_call_docstring:
968 call_ds = None
1024 call_ds = None
969 if call_ds:
1025 if call_ds:
970 out['call_docstring'] = call_ds
1026 out['call_docstring'] = call_ds
971
1027
972 return object_info(**out)
1028 return object_info(**out)
973
1029
974 @staticmethod
1030 @staticmethod
975 def _source_contains_docstring(src, doc):
1031 def _source_contains_docstring(src, doc):
976 """
1032 """
977 Check whether the source *src* contains the docstring *doc*.
1033 Check whether the source *src* contains the docstring *doc*.
978
1034
979 This is is helper function to skip displaying the docstring if the
1035 This is is helper function to skip displaying the docstring if the
980 source already contains it, avoiding repetition of information.
1036 source already contains it, avoiding repetition of information.
981 """
1037 """
982 try:
1038 try:
983 def_node, = ast.parse(dedent(src)).body
1039 (def_node,) = ast.parse(dedent(src)).body
984 return ast.get_docstring(def_node) == doc
1040 return ast.get_docstring(def_node) == doc # type: ignore[arg-type]
985 except Exception:
1041 except Exception:
986 # The source can become invalid or even non-existent (because it
1042 # The source can become invalid or even non-existent (because it
987 # is re-fetched from the source file) so the above code fail in
1043 # is re-fetched from the source file) so the above code fail in
988 # arbitrary ways.
1044 # arbitrary ways.
989 return False
1045 return False
990
1046
991 def psearch(self,pattern,ns_table,ns_search=[],
1047 def psearch(self,pattern,ns_table,ns_search=[],
992 ignore_case=False,show_all=False, *, list_types=False):
1048 ignore_case=False,show_all=False, *, list_types=False):
993 """Search namespaces with wildcards for objects.
1049 """Search namespaces with wildcards for objects.
994
1050
995 Arguments:
1051 Arguments:
996
1052
997 - pattern: string containing shell-like wildcards to use in namespace
1053 - pattern: string containing shell-like wildcards to use in namespace
998 searches and optionally a type specification to narrow the search to
1054 searches and optionally a type specification to narrow the search to
999 objects of that type.
1055 objects of that type.
1000
1056
1001 - ns_table: dict of name->namespaces for search.
1057 - ns_table: dict of name->namespaces for search.
1002
1058
1003 Optional arguments:
1059 Optional arguments:
1004
1060
1005 - ns_search: list of namespace names to include in search.
1061 - ns_search: list of namespace names to include in search.
1006
1062
1007 - ignore_case(False): make the search case-insensitive.
1063 - ignore_case(False): make the search case-insensitive.
1008
1064
1009 - show_all(False): show all names, including those starting with
1065 - show_all(False): show all names, including those starting with
1010 underscores.
1066 underscores.
1011
1067
1012 - list_types(False): list all available object types for object matching.
1068 - list_types(False): list all available object types for object matching.
1013 """
1069 """
1014 #print 'ps pattern:<%r>' % pattern # dbg
1070 #print 'ps pattern:<%r>' % pattern # dbg
1015
1071
1016 # defaults
1072 # defaults
1017 type_pattern = 'all'
1073 type_pattern = 'all'
1018 filter = ''
1074 filter = ''
1019
1075
1020 # list all object types
1076 # list all object types
1021 if list_types:
1077 if list_types:
1022 page.page('\n'.join(sorted(typestr2type)))
1078 page.page('\n'.join(sorted(typestr2type)))
1023 return
1079 return
1024
1080
1025 cmds = pattern.split()
1081 cmds = pattern.split()
1026 len_cmds = len(cmds)
1082 len_cmds = len(cmds)
1027 if len_cmds == 1:
1083 if len_cmds == 1:
1028 # Only filter pattern given
1084 # Only filter pattern given
1029 filter = cmds[0]
1085 filter = cmds[0]
1030 elif len_cmds == 2:
1086 elif len_cmds == 2:
1031 # Both filter and type specified
1087 # Both filter and type specified
1032 filter,type_pattern = cmds
1088 filter,type_pattern = cmds
1033 else:
1089 else:
1034 raise ValueError('invalid argument string for psearch: <%s>' %
1090 raise ValueError('invalid argument string for psearch: <%s>' %
1035 pattern)
1091 pattern)
1036
1092
1037 # filter search namespaces
1093 # filter search namespaces
1038 for name in ns_search:
1094 for name in ns_search:
1039 if name not in ns_table:
1095 if name not in ns_table:
1040 raise ValueError('invalid namespace <%s>. Valid names: %s' %
1096 raise ValueError('invalid namespace <%s>. Valid names: %s' %
1041 (name,ns_table.keys()))
1097 (name,ns_table.keys()))
1042
1098
1043 #print 'type_pattern:',type_pattern # dbg
1099 #print 'type_pattern:',type_pattern # dbg
1044 search_result, namespaces_seen = set(), set()
1100 search_result, namespaces_seen = set(), set()
1045 for ns_name in ns_search:
1101 for ns_name in ns_search:
1046 ns = ns_table[ns_name]
1102 ns = ns_table[ns_name]
1047 # Normally, locals and globals are the same, so we just check one.
1103 # Normally, locals and globals are the same, so we just check one.
1048 if id(ns) in namespaces_seen:
1104 if id(ns) in namespaces_seen:
1049 continue
1105 continue
1050 namespaces_seen.add(id(ns))
1106 namespaces_seen.add(id(ns))
1051 tmp_res = list_namespace(ns, type_pattern, filter,
1107 tmp_res = list_namespace(ns, type_pattern, filter,
1052 ignore_case=ignore_case, show_all=show_all)
1108 ignore_case=ignore_case, show_all=show_all)
1053 search_result.update(tmp_res)
1109 search_result.update(tmp_res)
1054
1110
1055 page.page('\n'.join(sorted(search_result)))
1111 page.page('\n'.join(sorted(search_result)))
1056
1112
1057
1113
1058 def _render_signature(obj_signature, obj_name) -> str:
1114 def _render_signature(obj_signature, obj_name) -> str:
1059 """
1115 """
1060 This was mostly taken from inspect.Signature.__str__.
1116 This was mostly taken from inspect.Signature.__str__.
1061 Look there for the comments.
1117 Look there for the comments.
1062 The only change is to add linebreaks when this gets too long.
1118 The only change is to add linebreaks when this gets too long.
1063 """
1119 """
1064 result = []
1120 result = []
1065 pos_only = False
1121 pos_only = False
1066 kw_only = True
1122 kw_only = True
1067 for param in obj_signature.parameters.values():
1123 for param in obj_signature.parameters.values():
1068 if param.kind == inspect.Parameter.POSITIONAL_ONLY:
1124 if param.kind == inspect.Parameter.POSITIONAL_ONLY:
1069 pos_only = True
1125 pos_only = True
1070 elif pos_only:
1126 elif pos_only:
1071 result.append('/')
1127 result.append('/')
1072 pos_only = False
1128 pos_only = False
1073
1129
1074 if param.kind == inspect.Parameter.VAR_POSITIONAL:
1130 if param.kind == inspect.Parameter.VAR_POSITIONAL:
1075 kw_only = False
1131 kw_only = False
1076 elif param.kind == inspect.Parameter.KEYWORD_ONLY and kw_only:
1132 elif param.kind == inspect.Parameter.KEYWORD_ONLY and kw_only:
1077 result.append('*')
1133 result.append('*')
1078 kw_only = False
1134 kw_only = False
1079
1135
1080 result.append(str(param))
1136 result.append(str(param))
1081
1137
1082 if pos_only:
1138 if pos_only:
1083 result.append('/')
1139 result.append('/')
1084
1140
1085 # add up name, parameters, braces (2), and commas
1141 # add up name, parameters, braces (2), and commas
1086 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1142 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1087 # This doesn’t fit behind β€œSignature: ” in an inspect window.
1143 # This doesn’t fit behind β€œSignature: ” in an inspect window.
1088 rendered = '{}(\n{})'.format(obj_name, ''.join(
1144 rendered = '{}(\n{})'.format(obj_name, ''.join(
1089 ' {},\n'.format(r) for r in result)
1145 ' {},\n'.format(r) for r in result)
1090 )
1146 )
1091 else:
1147 else:
1092 rendered = '{}({})'.format(obj_name, ', '.join(result))
1148 rendered = '{}({})'.format(obj_name, ', '.join(result))
1093
1149
1094 if obj_signature.return_annotation is not inspect._empty:
1150 if obj_signature.return_annotation is not inspect._empty:
1095 anno = inspect.formatannotation(obj_signature.return_annotation)
1151 anno = inspect.formatannotation(obj_signature.return_annotation)
1096 rendered += ' -> {}'.format(anno)
1152 rendered += ' -> {}'.format(anno)
1097
1153
1098 return rendered
1154 return rendered
@@ -1,533 +1,570 b''
1 """Tests for the object inspection functionality.
1 """Tests for the object inspection functionality.
2 """
2 """
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 from contextlib import contextmanager
8 from contextlib import contextmanager
9 from inspect import signature, Signature, Parameter
9 from inspect import signature, Signature, Parameter
10 import inspect
10 import inspect
11 import os
11 import os
12 import pytest
12 import pytest
13 import re
13 import re
14 import sys
14 import sys
15
15
16 from .. import oinspect
16 from .. import oinspect
17
17
18 from decorator import decorator
18 from decorator import decorator
19
19
20 from IPython.testing.tools import AssertPrints, AssertNotPrints
20 from IPython.testing.tools import AssertPrints, AssertNotPrints
21 from IPython.utils.path import compress_user
21 from IPython.utils.path import compress_user
22
22
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Globals and constants
25 # Globals and constants
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 inspector = None
28 inspector = None
29
29
30 def setup_module():
30 def setup_module():
31 global inspector
31 global inspector
32 inspector = oinspect.Inspector()
32 inspector = oinspect.Inspector()
33
33
34
34
35 class SourceModuleMainTest:
35 class SourceModuleMainTest:
36 __module__ = "__main__"
36 __module__ = "__main__"
37
37
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Local utilities
40 # Local utilities
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 # WARNING: since this test checks the line number where a function is
43 # WARNING: since this test checks the line number where a function is
44 # defined, if any code is inserted above, the following line will need to be
44 # defined, if any code is inserted above, the following line will need to be
45 # updated. Do NOT insert any whitespace between the next line and the function
45 # updated. Do NOT insert any whitespace between the next line and the function
46 # definition below.
46 # definition below.
47 THIS_LINE_NUMBER = 47 # Put here the actual number of this line
47 THIS_LINE_NUMBER = 47 # Put here the actual number of this line
48
48
49
49
50 def test_find_source_lines():
50 def test_find_source_lines():
51 assert oinspect.find_source_lines(test_find_source_lines) == THIS_LINE_NUMBER + 3
51 assert oinspect.find_source_lines(test_find_source_lines) == THIS_LINE_NUMBER + 3
52 assert oinspect.find_source_lines(type) is None
52 assert oinspect.find_source_lines(type) is None
53 assert oinspect.find_source_lines(SourceModuleMainTest) is None
53 assert oinspect.find_source_lines(SourceModuleMainTest) is None
54 assert oinspect.find_source_lines(SourceModuleMainTest()) is None
54 assert oinspect.find_source_lines(SourceModuleMainTest()) is None
55
55
56
56
57 def test_getsource():
57 def test_getsource():
58 assert oinspect.getsource(type) is None
58 assert oinspect.getsource(type) is None
59 assert oinspect.getsource(SourceModuleMainTest) is None
59 assert oinspect.getsource(SourceModuleMainTest) is None
60 assert oinspect.getsource(SourceModuleMainTest()) is None
60 assert oinspect.getsource(SourceModuleMainTest()) is None
61
61
62
62
63 def test_inspect_getfile_raises_exception():
63 def test_inspect_getfile_raises_exception():
64 """Check oinspect.find_file/getsource/find_source_lines expectations"""
64 """Check oinspect.find_file/getsource/find_source_lines expectations"""
65 with pytest.raises(TypeError):
65 with pytest.raises(TypeError):
66 inspect.getfile(type)
66 inspect.getfile(type)
67 with pytest.raises(OSError if sys.version_info >= (3, 10) else TypeError):
67 with pytest.raises(OSError if sys.version_info >= (3, 10) else TypeError):
68 inspect.getfile(SourceModuleMainTest)
68 inspect.getfile(SourceModuleMainTest)
69
69
70
70
71 # A couple of utilities to ensure these tests work the same from a source or a
71 # A couple of utilities to ensure these tests work the same from a source or a
72 # binary install
72 # binary install
73 def pyfile(fname):
73 def pyfile(fname):
74 return os.path.normcase(re.sub('.py[co]$', '.py', fname))
74 return os.path.normcase(re.sub('.py[co]$', '.py', fname))
75
75
76
76
77 def match_pyfiles(f1, f2):
77 def match_pyfiles(f1, f2):
78 assert pyfile(f1) == pyfile(f2)
78 assert pyfile(f1) == pyfile(f2)
79
79
80
80
81 def test_find_file():
81 def test_find_file():
82 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
82 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
83 assert oinspect.find_file(type) is None
83 assert oinspect.find_file(type) is None
84 assert oinspect.find_file(SourceModuleMainTest) is None
84 assert oinspect.find_file(SourceModuleMainTest) is None
85 assert oinspect.find_file(SourceModuleMainTest()) is None
85 assert oinspect.find_file(SourceModuleMainTest()) is None
86
86
87
87
88 def test_find_file_decorated1():
88 def test_find_file_decorated1():
89
89
90 @decorator
90 @decorator
91 def noop1(f):
91 def noop1(f):
92 def wrapper(*a, **kw):
92 def wrapper(*a, **kw):
93 return f(*a, **kw)
93 return f(*a, **kw)
94 return wrapper
94 return wrapper
95
95
96 @noop1
96 @noop1
97 def f(x):
97 def f(x):
98 "My docstring"
98 "My docstring"
99
99
100 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
100 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
101 assert f.__doc__ == "My docstring"
101 assert f.__doc__ == "My docstring"
102
102
103
103
104 def test_find_file_decorated2():
104 def test_find_file_decorated2():
105
105
106 @decorator
106 @decorator
107 def noop2(f, *a, **kw):
107 def noop2(f, *a, **kw):
108 return f(*a, **kw)
108 return f(*a, **kw)
109
109
110 @noop2
110 @noop2
111 @noop2
111 @noop2
112 @noop2
112 @noop2
113 def f(x):
113 def f(x):
114 "My docstring 2"
114 "My docstring 2"
115
115
116 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
116 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
117 assert f.__doc__ == "My docstring 2"
117 assert f.__doc__ == "My docstring 2"
118
118
119
119
120 def test_find_file_magic():
120 def test_find_file_magic():
121 run = ip.find_line_magic('run')
121 run = ip.find_line_magic('run')
122 assert oinspect.find_file(run) is not None
122 assert oinspect.find_file(run) is not None
123
123
124
124
125 # A few generic objects we can then inspect in the tests below
125 # A few generic objects we can then inspect in the tests below
126
126
127 class Call(object):
127 class Call(object):
128 """This is the class docstring."""
128 """This is the class docstring."""
129
129
130 def __init__(self, x, y=1):
130 def __init__(self, x, y=1):
131 """This is the constructor docstring."""
131 """This is the constructor docstring."""
132
132
133 def __call__(self, *a, **kw):
133 def __call__(self, *a, **kw):
134 """This is the call docstring."""
134 """This is the call docstring."""
135
135
136 def method(self, x, z=2):
136 def method(self, x, z=2):
137 """Some method's docstring"""
137 """Some method's docstring"""
138
138
139 class HasSignature(object):
139 class HasSignature(object):
140 """This is the class docstring."""
140 """This is the class docstring."""
141 __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)])
141 __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)])
142
142
143 def __init__(self, *args):
143 def __init__(self, *args):
144 """This is the init docstring"""
144 """This is the init docstring"""
145
145
146
146
147 class SimpleClass(object):
147 class SimpleClass(object):
148 def method(self, x, z=2):
148 def method(self, x, z=2):
149 """Some method's docstring"""
149 """Some method's docstring"""
150
150
151
151
152 class Awkward(object):
152 class Awkward(object):
153 def __getattr__(self, name):
153 def __getattr__(self, name):
154 raise Exception(name)
154 raise Exception(name)
155
155
156 class NoBoolCall:
156 class NoBoolCall:
157 """
157 """
158 callable with `__bool__` raising should still be inspect-able.
158 callable with `__bool__` raising should still be inspect-able.
159 """
159 """
160
160
161 def __call__(self):
161 def __call__(self):
162 """does nothing"""
162 """does nothing"""
163 pass
163 pass
164
164
165 def __bool__(self):
165 def __bool__(self):
166 """just raise NotImplemented"""
166 """just raise NotImplemented"""
167 raise NotImplementedError('Must be implemented')
167 raise NotImplementedError('Must be implemented')
168
168
169
169
170 class SerialLiar(object):
170 class SerialLiar(object):
171 """Attribute accesses always get another copy of the same class.
171 """Attribute accesses always get another copy of the same class.
172
172
173 unittest.mock.call does something similar, but it's not ideal for testing
173 unittest.mock.call does something similar, but it's not ideal for testing
174 as the failure mode is to eat all your RAM. This gives up after 10k levels.
174 as the failure mode is to eat all your RAM. This gives up after 10k levels.
175 """
175 """
176 def __init__(self, max_fibbing_twig, lies_told=0):
176 def __init__(self, max_fibbing_twig, lies_told=0):
177 if lies_told > 10000:
177 if lies_told > 10000:
178 raise RuntimeError('Nose too long, honesty is the best policy')
178 raise RuntimeError('Nose too long, honesty is the best policy')
179 self.max_fibbing_twig = max_fibbing_twig
179 self.max_fibbing_twig = max_fibbing_twig
180 self.lies_told = lies_told
180 self.lies_told = lies_told
181 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
181 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
182
182
183 def __getattr__(self, item):
183 def __getattr__(self, item):
184 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
184 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
185
185
186 #-----------------------------------------------------------------------------
186 #-----------------------------------------------------------------------------
187 # Tests
187 # Tests
188 #-----------------------------------------------------------------------------
188 #-----------------------------------------------------------------------------
189
189
190 def test_info():
190 def test_info():
191 "Check that Inspector.info fills out various fields as expected."
191 "Check that Inspector.info fills out various fields as expected."
192 i = inspector.info(Call, oname="Call")
192 i = inspector.info(Call, oname="Call")
193 assert i["type_name"] == "type"
193 assert i["type_name"] == "type"
194 expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
194 expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
195 assert i["base_class"] == expected_class
195 assert i["base_class"] == expected_class
196 assert re.search(
196 assert re.search(
197 "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
197 "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
198 i["string_form"],
198 i["string_form"],
199 )
199 )
200 fname = __file__
200 fname = __file__
201 if fname.endswith(".pyc"):
201 if fname.endswith(".pyc"):
202 fname = fname[:-1]
202 fname = fname[:-1]
203 # case-insensitive comparison needed on some filesystems
203 # case-insensitive comparison needed on some filesystems
204 # e.g. Windows:
204 # e.g. Windows:
205 assert i["file"].lower() == compress_user(fname).lower()
205 assert i["file"].lower() == compress_user(fname).lower()
206 assert i["definition"] == None
206 assert i["definition"] == None
207 assert i["docstring"] == Call.__doc__
207 assert i["docstring"] == Call.__doc__
208 assert i["source"] == None
208 assert i["source"] == None
209 assert i["isclass"] is True
209 assert i["isclass"] is True
210 assert i["init_definition"] == "Call(x, y=1)"
210 assert i["init_definition"] == "Call(x, y=1)"
211 assert i["init_docstring"] == Call.__init__.__doc__
211 assert i["init_docstring"] == Call.__init__.__doc__
212
212
213 i = inspector.info(Call, detail_level=1)
213 i = inspector.info(Call, detail_level=1)
214 assert i["source"] is not None
214 assert i["source"] is not None
215 assert i["docstring"] == None
215 assert i["docstring"] == None
216
216
217 c = Call(1)
217 c = Call(1)
218 c.__doc__ = "Modified instance docstring"
218 c.__doc__ = "Modified instance docstring"
219 i = inspector.info(c)
219 i = inspector.info(c)
220 assert i["type_name"] == "Call"
220 assert i["type_name"] == "Call"
221 assert i["docstring"] == "Modified instance docstring"
221 assert i["docstring"] == "Modified instance docstring"
222 assert i["class_docstring"] == Call.__doc__
222 assert i["class_docstring"] == Call.__doc__
223 assert i["init_docstring"] == Call.__init__.__doc__
223 assert i["init_docstring"] == Call.__init__.__doc__
224 assert i["call_docstring"] == Call.__call__.__doc__
224 assert i["call_docstring"] == Call.__call__.__doc__
225
225
226
226
227 def test_class_signature():
227 def test_class_signature():
228 info = inspector.info(HasSignature, "HasSignature")
228 info = inspector.info(HasSignature, "HasSignature")
229 assert info["init_definition"] == "HasSignature(test)"
229 assert info["init_definition"] == "HasSignature(test)"
230 assert info["init_docstring"] == HasSignature.__init__.__doc__
230 assert info["init_docstring"] == HasSignature.__init__.__doc__
231
231
232
232
233 def test_info_awkward():
233 def test_info_awkward():
234 # Just test that this doesn't throw an error.
234 # Just test that this doesn't throw an error.
235 inspector.info(Awkward())
235 inspector.info(Awkward())
236
236
237 def test_bool_raise():
237 def test_bool_raise():
238 inspector.info(NoBoolCall())
238 inspector.info(NoBoolCall())
239
239
240 def test_info_serialliar():
240 def test_info_serialliar():
241 fib_tracker = [0]
241 fib_tracker = [0]
242 inspector.info(SerialLiar(fib_tracker))
242 inspector.info(SerialLiar(fib_tracker))
243
243
244 # Nested attribute access should be cut off at 100 levels deep to avoid
244 # Nested attribute access should be cut off at 100 levels deep to avoid
245 # infinite loops: https://github.com/ipython/ipython/issues/9122
245 # infinite loops: https://github.com/ipython/ipython/issues/9122
246 assert fib_tracker[0] < 9000
246 assert fib_tracker[0] < 9000
247
247
248 def support_function_one(x, y=2, *a, **kw):
248 def support_function_one(x, y=2, *a, **kw):
249 """A simple function."""
249 """A simple function."""
250
250
251 def test_calldef_none():
251 def test_calldef_none():
252 # We should ignore __call__ for all of these.
252 # We should ignore __call__ for all of these.
253 for obj in [support_function_one, SimpleClass().method, any, str.upper]:
253 for obj in [support_function_one, SimpleClass().method, any, str.upper]:
254 i = inspector.info(obj)
254 i = inspector.info(obj)
255 assert i["call_def"] is None
255 assert i["call_def"] is None
256
256
257
257
258 def f_kwarg(pos, *, kwonly):
258 def f_kwarg(pos, *, kwonly):
259 pass
259 pass
260
260
261 def test_definition_kwonlyargs():
261 def test_definition_kwonlyargs():
262 i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore
262 i = inspector.info(f_kwarg, oname="f_kwarg") # analysis:ignore
263 assert i["definition"] == "f_kwarg(pos, *, kwonly)"
263 assert i["definition"] == "f_kwarg(pos, *, kwonly)"
264
264
265
265
266 def test_getdoc():
266 def test_getdoc():
267 class A(object):
267 class A(object):
268 """standard docstring"""
268 """standard docstring"""
269 pass
269 pass
270
270
271 class B(object):
271 class B(object):
272 """standard docstring"""
272 """standard docstring"""
273 def getdoc(self):
273 def getdoc(self):
274 return "custom docstring"
274 return "custom docstring"
275
275
276 class C(object):
276 class C(object):
277 """standard docstring"""
277 """standard docstring"""
278 def getdoc(self):
278 def getdoc(self):
279 return None
279 return None
280
280
281 a = A()
281 a = A()
282 b = B()
282 b = B()
283 c = C()
283 c = C()
284
284
285 assert oinspect.getdoc(a) == "standard docstring"
285 assert oinspect.getdoc(a) == "standard docstring"
286 assert oinspect.getdoc(b) == "custom docstring"
286 assert oinspect.getdoc(b) == "custom docstring"
287 assert oinspect.getdoc(c) == "standard docstring"
287 assert oinspect.getdoc(c) == "standard docstring"
288
288
289
289
290 def test_empty_property_has_no_source():
290 def test_empty_property_has_no_source():
291 i = inspector.info(property(), detail_level=1)
291 i = inspector.info(property(), detail_level=1)
292 assert i["source"] is None
292 assert i["source"] is None
293
293
294
294
295 def test_property_sources():
295 def test_property_sources():
296 # A simple adder whose source and signature stays
296 # A simple adder whose source and signature stays
297 # the same across Python distributions
297 # the same across Python distributions
298 def simple_add(a, b):
298 def simple_add(a, b):
299 "Adds two numbers"
299 "Adds two numbers"
300 return a + b
300 return a + b
301
301
302 class A(object):
302 class A(object):
303 @property
303 @property
304 def foo(self):
304 def foo(self):
305 return 'bar'
305 return 'bar'
306
306
307 foo = foo.setter(lambda self, v: setattr(self, 'bar', v))
307 foo = foo.setter(lambda self, v: setattr(self, 'bar', v))
308
308
309 dname = property(oinspect.getdoc)
309 dname = property(oinspect.getdoc)
310 adder = property(simple_add)
310 adder = property(simple_add)
311
311
312 i = inspector.info(A.foo, detail_level=1)
312 i = inspector.info(A.foo, detail_level=1)
313 assert "def foo(self):" in i["source"]
313 assert "def foo(self):" in i["source"]
314 assert "lambda self, v:" in i["source"]
314 assert "lambda self, v:" in i["source"]
315
315
316 i = inspector.info(A.dname, detail_level=1)
316 i = inspector.info(A.dname, detail_level=1)
317 assert "def getdoc(obj)" in i["source"]
317 assert "def getdoc(obj)" in i["source"]
318
318
319 i = inspector.info(A.adder, detail_level=1)
319 i = inspector.info(A.adder, detail_level=1)
320 assert "def simple_add(a, b)" in i["source"]
320 assert "def simple_add(a, b)" in i["source"]
321
321
322
322
323 def test_property_docstring_is_in_info_for_detail_level_0():
323 def test_property_docstring_is_in_info_for_detail_level_0():
324 class A(object):
324 class A(object):
325 @property
325 @property
326 def foobar(self):
326 def foobar(self):
327 """This is `foobar` property."""
327 """This is `foobar` property."""
328 pass
328 pass
329
329
330 ip.user_ns["a_obj"] = A()
330 ip.user_ns["a_obj"] = A()
331 assert (
331 assert (
332 "This is `foobar` property."
332 "This is `foobar` property."
333 == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"]
333 == ip.object_inspect("a_obj.foobar", detail_level=0)["docstring"]
334 )
334 )
335
335
336 ip.user_ns["a_cls"] = A
336 ip.user_ns["a_cls"] = A
337 assert (
337 assert (
338 "This is `foobar` property."
338 "This is `foobar` property."
339 == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"]
339 == ip.object_inspect("a_cls.foobar", detail_level=0)["docstring"]
340 )
340 )
341
341
342
342
343 def test_pdef():
343 def test_pdef():
344 # See gh-1914
344 # See gh-1914
345 def foo(): pass
345 def foo(): pass
346 inspector.pdef(foo, 'foo')
346 inspector.pdef(foo, 'foo')
347
347
348
348
349 @contextmanager
349 @contextmanager
350 def cleanup_user_ns(**kwargs):
350 def cleanup_user_ns(**kwargs):
351 """
351 """
352 On exit delete all the keys that were not in user_ns before entering.
352 On exit delete all the keys that were not in user_ns before entering.
353
353
354 It does not restore old values !
354 It does not restore old values !
355
355
356 Parameters
356 Parameters
357 ----------
357 ----------
358
358
359 **kwargs
359 **kwargs
360 used to update ip.user_ns
360 used to update ip.user_ns
361
361
362 """
362 """
363 try:
363 try:
364 known = set(ip.user_ns.keys())
364 known = set(ip.user_ns.keys())
365 ip.user_ns.update(kwargs)
365 ip.user_ns.update(kwargs)
366 yield
366 yield
367 finally:
367 finally:
368 added = set(ip.user_ns.keys()) - known
368 added = set(ip.user_ns.keys()) - known
369 for k in added:
369 for k in added:
370 del ip.user_ns[k]
370 del ip.user_ns[k]
371
371
372
372
373 def test_pinfo_getindex():
373 def test_pinfo_getindex():
374 def dummy():
374 def dummy():
375 """
375 """
376 MARKER
376 MARKER
377 """
377 """
378
378
379 container = [dummy]
379 container = [dummy]
380 with cleanup_user_ns(container=container):
380 with cleanup_user_ns(container=container):
381 with AssertPrints("MARKER"):
381 with AssertPrints("MARKER"):
382 ip._inspect("pinfo", "container[0]", detail_level=0)
382 ip._inspect("pinfo", "container[0]", detail_level=0)
383 assert "container" not in ip.user_ns.keys()
383 assert "container" not in ip.user_ns.keys()
384
384
385
385
386 def test_qmark_getindex():
386 def test_qmark_getindex():
387 def dummy():
387 def dummy():
388 """
388 """
389 MARKER 2
389 MARKER 2
390 """
390 """
391
391
392 container = [dummy]
392 container = [dummy]
393 with cleanup_user_ns(container=container):
393 with cleanup_user_ns(container=container):
394 with AssertPrints("MARKER 2"):
394 with AssertPrints("MARKER 2"):
395 ip.run_cell("container[0]?")
395 ip.run_cell("container[0]?")
396 assert "container" not in ip.user_ns.keys()
396 assert "container" not in ip.user_ns.keys()
397
397
398
398
399 def test_qmark_getindex_negatif():
399 def test_qmark_getindex_negatif():
400 def dummy():
400 def dummy():
401 """
401 """
402 MARKER 3
402 MARKER 3
403 """
403 """
404
404
405 container = [dummy]
405 container = [dummy]
406 with cleanup_user_ns(container=container):
406 with cleanup_user_ns(container=container):
407 with AssertPrints("MARKER 3"):
407 with AssertPrints("MARKER 3"):
408 ip.run_cell("container[-1]?")
408 ip.run_cell("container[-1]?")
409 assert "container" not in ip.user_ns.keys()
409 assert "container" not in ip.user_ns.keys()
410
410
411
411
412
412
413 def test_pinfo_nonascii():
413 def test_pinfo_nonascii():
414 # See gh-1177
414 # See gh-1177
415 from . import nonascii2
415 from . import nonascii2
416 ip.user_ns['nonascii2'] = nonascii2
416 ip.user_ns['nonascii2'] = nonascii2
417 ip._inspect('pinfo', 'nonascii2', detail_level=1)
417 ip._inspect('pinfo', 'nonascii2', detail_level=1)
418
418
419 def test_pinfo_type():
419 def test_pinfo_type():
420 """
420 """
421 type can fail in various edge case, for example `type.__subclass__()`
421 type can fail in various edge case, for example `type.__subclass__()`
422 """
422 """
423 ip._inspect('pinfo', 'type')
423 ip._inspect('pinfo', 'type')
424
424
425
425
426 def test_pinfo_docstring_no_source():
426 def test_pinfo_docstring_no_source():
427 """Docstring should be included with detail_level=1 if there is no source"""
427 """Docstring should be included with detail_level=1 if there is no source"""
428 with AssertPrints('Docstring:'):
428 with AssertPrints('Docstring:'):
429 ip._inspect('pinfo', 'str.format', detail_level=0)
429 ip._inspect('pinfo', 'str.format', detail_level=0)
430 with AssertPrints('Docstring:'):
430 with AssertPrints('Docstring:'):
431 ip._inspect('pinfo', 'str.format', detail_level=1)
431 ip._inspect('pinfo', 'str.format', detail_level=1)
432
432
433
433
434 def test_pinfo_no_docstring_if_source():
434 def test_pinfo_no_docstring_if_source():
435 """Docstring should not be included with detail_level=1 if source is found"""
435 """Docstring should not be included with detail_level=1 if source is found"""
436 def foo():
436 def foo():
437 """foo has a docstring"""
437 """foo has a docstring"""
438
438
439 ip.user_ns['foo'] = foo
439 ip.user_ns['foo'] = foo
440
440
441 with AssertPrints('Docstring:'):
441 with AssertPrints('Docstring:'):
442 ip._inspect('pinfo', 'foo', detail_level=0)
442 ip._inspect('pinfo', 'foo', detail_level=0)
443 with AssertPrints('Source:'):
443 with AssertPrints('Source:'):
444 ip._inspect('pinfo', 'foo', detail_level=1)
444 ip._inspect('pinfo', 'foo', detail_level=1)
445 with AssertNotPrints('Docstring:'):
445 with AssertNotPrints('Docstring:'):
446 ip._inspect('pinfo', 'foo', detail_level=1)
446 ip._inspect('pinfo', 'foo', detail_level=1)
447
447
448
448
449 def test_pinfo_docstring_if_detail_and_no_source():
449 def test_pinfo_docstring_if_detail_and_no_source():
450 """ Docstring should be displayed if source info not available """
450 """ Docstring should be displayed if source info not available """
451 obj_def = '''class Foo(object):
451 obj_def = '''class Foo(object):
452 """ This is a docstring for Foo """
452 """ This is a docstring for Foo """
453 def bar(self):
453 def bar(self):
454 """ This is a docstring for Foo.bar """
454 """ This is a docstring for Foo.bar """
455 pass
455 pass
456 '''
456 '''
457
457
458 ip.run_cell(obj_def)
458 ip.run_cell(obj_def)
459 ip.run_cell('foo = Foo()')
459 ip.run_cell('foo = Foo()')
460
460
461 with AssertNotPrints("Source:"):
461 with AssertNotPrints("Source:"):
462 with AssertPrints('Docstring:'):
462 with AssertPrints('Docstring:'):
463 ip._inspect('pinfo', 'foo', detail_level=0)
463 ip._inspect('pinfo', 'foo', detail_level=0)
464 with AssertPrints('Docstring:'):
464 with AssertPrints('Docstring:'):
465 ip._inspect('pinfo', 'foo', detail_level=1)
465 ip._inspect('pinfo', 'foo', detail_level=1)
466 with AssertPrints('Docstring:'):
466 with AssertPrints('Docstring:'):
467 ip._inspect('pinfo', 'foo.bar', detail_level=0)
467 ip._inspect('pinfo', 'foo.bar', detail_level=0)
468
468
469 with AssertNotPrints('Docstring:'):
469 with AssertNotPrints('Docstring:'):
470 with AssertPrints('Source:'):
470 with AssertPrints('Source:'):
471 ip._inspect('pinfo', 'foo.bar', detail_level=1)
471 ip._inspect('pinfo', 'foo.bar', detail_level=1)
472
472
473
473
474 def test_pinfo_docstring_dynamic():
475 obj_def = """class Bar:
476 __custom_documentations__ = {
477 "prop" : "cdoc for prop",
478 "non_exist" : "cdoc for non_exist",
479 }
480 @property
481 def prop(self):
482 '''
483 Docstring for prop
484 '''
485 return self._prop
486
487 @prop.setter
488 def prop(self, v):
489 self._prop = v
490 """
491 ip.run_cell(obj_def)
492
493 ip.run_cell("b = Bar()")
494
495 with AssertPrints("Docstring: cdoc for prop"):
496 ip.run_line_magic("pinfo", "b.prop")
497
498 with AssertPrints("Docstring: cdoc for non_exist"):
499 ip.run_line_magic("pinfo", "b.non_exist")
500
501 with AssertPrints("Docstring: cdoc for prop"):
502 ip.run_cell("b.prop?")
503
504 with AssertPrints("Docstring: cdoc for non_exist"):
505 ip.run_cell("b.non_exist?")
506
507 with AssertPrints("Docstring: <no docstring>"):
508 ip.run_cell("b.undefined?")
509
510
474 def test_pinfo_magic():
511 def test_pinfo_magic():
475 with AssertPrints('Docstring:'):
512 with AssertPrints("Docstring:"):
476 ip._inspect('pinfo', 'lsmagic', detail_level=0)
513 ip._inspect("pinfo", "lsmagic", detail_level=0)
477
514
478 with AssertPrints('Source:'):
515 with AssertPrints("Source:"):
479 ip._inspect('pinfo', 'lsmagic', detail_level=1)
516 ip._inspect("pinfo", "lsmagic", detail_level=1)
480
517
481
518
482 def test_init_colors():
519 def test_init_colors():
483 # ensure colors are not present in signature info
520 # ensure colors are not present in signature info
484 info = inspector.info(HasSignature)
521 info = inspector.info(HasSignature)
485 init_def = info["init_definition"]
522 init_def = info["init_definition"]
486 assert "[0m" not in init_def
523 assert "[0m" not in init_def
487
524
488
525
489 def test_builtin_init():
526 def test_builtin_init():
490 info = inspector.info(list)
527 info = inspector.info(list)
491 init_def = info['init_definition']
528 init_def = info['init_definition']
492 assert init_def is not None
529 assert init_def is not None
493
530
494
531
495 def test_render_signature_short():
532 def test_render_signature_short():
496 def short_fun(a=1): pass
533 def short_fun(a=1): pass
497 sig = oinspect._render_signature(
534 sig = oinspect._render_signature(
498 signature(short_fun),
535 signature(short_fun),
499 short_fun.__name__,
536 short_fun.__name__,
500 )
537 )
501 assert sig == "short_fun(a=1)"
538 assert sig == "short_fun(a=1)"
502
539
503
540
504 def test_render_signature_long():
541 def test_render_signature_long():
505 from typing import Optional
542 from typing import Optional
506
543
507 def long_function(
544 def long_function(
508 a_really_long_parameter: int,
545 a_really_long_parameter: int,
509 and_another_long_one: bool = False,
546 and_another_long_one: bool = False,
510 let_us_make_sure_this_is_looong: Optional[str] = None,
547 let_us_make_sure_this_is_looong: Optional[str] = None,
511 ) -> bool: pass
548 ) -> bool: pass
512
549
513 sig = oinspect._render_signature(
550 sig = oinspect._render_signature(
514 signature(long_function),
551 signature(long_function),
515 long_function.__name__,
552 long_function.__name__,
516 )
553 )
517 if sys.version_info >= (3, 9):
554 if sys.version_info >= (3, 9):
518 expected = """\
555 expected = """\
519 long_function(
556 long_function(
520 a_really_long_parameter: int,
557 a_really_long_parameter: int,
521 and_another_long_one: bool = False,
558 and_another_long_one: bool = False,
522 let_us_make_sure_this_is_looong: Optional[str] = None,
559 let_us_make_sure_this_is_looong: Optional[str] = None,
523 ) -> bool\
560 ) -> bool\
524 """
561 """
525 else:
562 else:
526 expected = """\
563 expected = """\
527 long_function(
564 long_function(
528 a_really_long_parameter: int,
565 a_really_long_parameter: int,
529 and_another_long_one: bool = False,
566 and_another_long_one: bool = False,
530 let_us_make_sure_this_is_looong: Union[str, NoneType] = None,
567 let_us_make_sure_this_is_looong: Union[str, NoneType] = None,
531 ) -> bool\
568 ) -> bool\
532 """
569 """
533 assert sig == expected
570 assert sig == expected
@@ -1,1499 +1,1574 b''
1 ============
1 ============
2 8.x Series
2 8.x Series
3 ============
3 ============
4
4
5 .. _version 8.12.0:
6
7
8 Dynamic documentation dispatch
9 ------------------------------
10
11
12 We are experimenting with dynamic documentation dispatch for object attribute.
13 See :ghissue:`13860`. The goal is to allow object to define documentation for
14 their attributes, properties, even when those are dynamically defined with
15 `__getattr__`.
16
17 In particular when those objects are base types it can be useful to show the
18 documentation
19
20
21 .. code::
22
23 In [1]: class User:
24 ...:
25 ...: __custom_documentations__ = {
26 ...: "first": "The first name of the user.",
27 ...: "last": "The last name of the user.",
28 ...: }
29 ...:
30 ...: first:str
31 ...: last:str
32 ...:
33 ...: def __init__(self, first, last):
34 ...: self.first = first
35 ...: self.last = last
36 ...:
37 ...: @property
38 ...: def full(self):
39 ...: """`self.first` and `self.last` joined by a space."""
40 ...: return self.first + " " + self.last
41 ...:
42 ...:
43 ...: user = Person('Jane', 'Doe')
44
45 In [2]: user.first?
46 Type: str
47 String form: Jane
48 Length: 4
49 Docstring: the first name of a the person object, a str
50 Class docstring:
51 ....
52
53 In [3]: user.last?
54 Type: str
55 String form: Doe
56 Length: 3
57 Docstring: the last name, also a str
58 ...
59
60
61 We can see here the symmetry with IPython looking for the docstring on the
62 properties::
63
64
65 In [4]: user.full?
66 HERE
67 Type: property
68 String form: <property object at 0x102bb15d0>
69 Docstring: first and last join by a space
70
71
72 Note that while in the above example we use a static dictionary, libraries may
73 decide to use a custom object that define ``__getitem__``, we caution against
74 using objects that would trigger computation to show documentation, but it is
75 sometime preferable for highly dynamic code that for example export ans API as
76 object.
77
78
79
5 .. _version 8.11.0:
80 .. _version 8.11.0:
6
81
7 IPython 8.11
82 IPython 8.11
8 ------------
83 ------------
9
84
10 Back on almost regular monthly schedule for IPython with end-of-month
85 Back on almost regular monthly schedule for IPython with end-of-month
11 really-late-Friday release to make sure some bugs are properly fixed.
86 really-late-Friday release to make sure some bugs are properly fixed.
12 Small addition of with a few new features, bugfix and UX improvements.
87 Small addition of with a few new features, bugfix and UX improvements.
13
88
14 This is a non-exhaustive list, but among other you will find:
89 This is a non-exhaustive list, but among other you will find:
15
90
16 Faster Traceback Highlighting
91 Faster Traceback Highlighting
17 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18
93
19 Resurrection of pre-IPython-8 traceback highlighting code.
94 Resurrection of pre-IPython-8 traceback highlighting code.
20
95
21 Really long and complicated files were slow to highlight in traceback with
96 Really long and complicated files were slow to highlight in traceback with
22 IPython 8 despite upstream improvement that make many case better. Therefore
97 IPython 8 despite upstream improvement that make many case better. Therefore
23 starting with IPython 8.11 when one of the highlighted file is more than 10 000
98 starting with IPython 8.11 when one of the highlighted file is more than 10 000
24 line long by default, we'll fallback to a faster path that does not have all the
99 line long by default, we'll fallback to a faster path that does not have all the
25 features of highlighting failing AST nodes.
100 features of highlighting failing AST nodes.
26
101
27 This can be configures by setting the value of
102 This can be configures by setting the value of
28 ``IPython.code.ultratb.FAST_THRESHOLD`` to an arbitrary low or large value.
103 ``IPython.code.ultratb.FAST_THRESHOLD`` to an arbitrary low or large value.
29
104
30
105
31 Autoreload verbosity
106 Autoreload verbosity
32 ~~~~~~~~~~~~~~~~~~~~
107 ~~~~~~~~~~~~~~~~~~~~
33
108
34 We introduce more descriptive names for the ``%autoreload`` parameter:
109 We introduce more descriptive names for the ``%autoreload`` parameter:
35
110
36 - ``%autoreload now`` (also ``%autoreload``) - perform autoreload immediately.
111 - ``%autoreload now`` (also ``%autoreload``) - perform autoreload immediately.
37 - ``%autoreload off`` (also ``%autoreload 0``) - turn off autoreload.
112 - ``%autoreload off`` (also ``%autoreload 0``) - turn off autoreload.
38 - ``%autoreload explicit`` (also ``%autoreload 1``) - turn on autoreload only for modules
113 - ``%autoreload explicit`` (also ``%autoreload 1``) - turn on autoreload only for modules
39 whitelisted by ``%aimport`` statements.
114 whitelisted by ``%aimport`` statements.
40 - ``%autoreload all`` (also ``%autoreload 2``) - turn on autoreload for all modules except those
115 - ``%autoreload all`` (also ``%autoreload 2``) - turn on autoreload for all modules except those
41 blacklisted by ``%aimport`` statements.
116 blacklisted by ``%aimport`` statements.
42 - ``%autoreload complete`` (also ``%autoreload 3``) - all the fatures of ``all`` but also adding new
117 - ``%autoreload complete`` (also ``%autoreload 3``) - all the fatures of ``all`` but also adding new
43 objects from the imported modules (see
118 objects from the imported modules (see
44 IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects).
119 IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects).
45
120
46 The original designations (e.g. "2") still work, and these new ones are case-insensitive.
121 The original designations (e.g. "2") still work, and these new ones are case-insensitive.
47
122
48 Additionally, the option ``--print`` or ``-p`` can be added to the line to print the names of
123 Additionally, the option ``--print`` or ``-p`` can be added to the line to print the names of
49 modules being reloaded. Similarly, ``--log`` or ``-l`` will output the names to the logger at INFO
124 modules being reloaded. Similarly, ``--log`` or ``-l`` will output the names to the logger at INFO
50 level. Both can be used simultaneously.
125 level. Both can be used simultaneously.
51
126
52 The parsing logic for ``%aimport`` is now improved such that modules can be whitelisted and
127 The parsing logic for ``%aimport`` is now improved such that modules can be whitelisted and
53 blacklisted in the same line, e.g. it's now possible to call ``%aimport os, -math`` to include
128 blacklisted in the same line, e.g. it's now possible to call ``%aimport os, -math`` to include
54 ``os`` for ``%autoreload explicit`` and exclude ``math`` for modes ``all`` and ``complete``.
129 ``os`` for ``%autoreload explicit`` and exclude ``math`` for modes ``all`` and ``complete``.
55
130
56 Terminal shortcuts customization
131 Terminal shortcuts customization
57 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
58
133
59 Previously modifying shortcuts was only possible by hooking into startup files
134 Previously modifying shortcuts was only possible by hooking into startup files
60 and practically limited to adding new shortcuts or removing all shortcuts bound
135 and practically limited to adding new shortcuts or removing all shortcuts bound
61 to a specific key. This release enables users to override existing terminal
136 to a specific key. This release enables users to override existing terminal
62 shortcuts, disable them or add new keybindings.
137 shortcuts, disable them or add new keybindings.
63
138
64 For example, to set the :kbd:`right` to accept a single character of auto-suggestion
139 For example, to set the :kbd:`right` to accept a single character of auto-suggestion
65 you could use::
140 you could use::
66
141
67 my_shortcuts = [
142 my_shortcuts = [
68 {
143 {
69 "command": "IPython:auto_suggest.accept_character",
144 "command": "IPython:auto_suggest.accept_character",
70 "new_keys": ["right"]
145 "new_keys": ["right"]
71 }
146 }
72 ]
147 ]
73 %config TerminalInteractiveShell.shortcuts = my_shortcuts
148 %config TerminalInteractiveShell.shortcuts = my_shortcuts
74
149
75 You can learn more in :std:configtrait:`TerminalInteractiveShell.shortcuts`
150 You can learn more in :std:configtrait:`TerminalInteractiveShell.shortcuts`
76 configuration reference.
151 configuration reference.
77
152
78 Miscellaneous
153 Miscellaneous
79 ~~~~~~~~~~~~~
154 ~~~~~~~~~~~~~
80
155
81 - ``%gui`` should now support PySide6. :ghpull:`13864`
156 - ``%gui`` should now support PySide6. :ghpull:`13864`
82 - Cli shortcuts can now be configured :ghpull:`13928`, see above.
157 - Cli shortcuts can now be configured :ghpull:`13928`, see above.
83 (note that there might be an issue with prompt_toolkit 3.0.37 and shortcut configuration).
158 (note that there might be an issue with prompt_toolkit 3.0.37 and shortcut configuration).
84
159
85 - Capture output should now respect ``;`` semicolon to suppress output.
160 - Capture output should now respect ``;`` semicolon to suppress output.
86 :ghpull:`13940`
161 :ghpull:`13940`
87 - Base64 encoded images (in jupyter frontend), will not have trailing newlines.
162 - Base64 encoded images (in jupyter frontend), will not have trailing newlines.
88 :ghpull:`13941`
163 :ghpull:`13941`
89
164
90 As usual you can find the full list of PRs on GitHub under `the 8.11 milestone
165 As usual you can find the full list of PRs on GitHub under `the 8.11 milestone
91 <https://github.com/ipython/ipython/milestone/113?closed=1>`__.
166 <https://github.com/ipython/ipython/milestone/113?closed=1>`__.
92
167
93 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
168 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
94 work on IPython and related libraries.
169 work on IPython and related libraries.
95
170
96 .. _version 8.10.0:
171 .. _version 8.10.0:
97
172
98 IPython 8.10
173 IPython 8.10
99 ------------
174 ------------
100
175
101 Out of schedule release of IPython with minor fixes to patch a potential CVE-2023-24816.
176 Out of schedule release of IPython with minor fixes to patch a potential CVE-2023-24816.
102 This is a really low severity CVE that you most likely are not affected by unless:
177 This is a really low severity CVE that you most likely are not affected by unless:
103
178
104 - You are on windows.
179 - You are on windows.
105 - You have a custom build of Python without ``_ctypes``
180 - You have a custom build of Python without ``_ctypes``
106 - You cd or start IPython or Jupyter in untrusted directory which names may be
181 - You cd or start IPython or Jupyter in untrusted directory which names may be
107 valid shell commands.
182 valid shell commands.
108
183
109 You can read more on `the advisory
184 You can read more on `the advisory
110 <https://github.com/ipython/ipython/security/advisories/GHSA-29gw-9793-fvw7>`__.
185 <https://github.com/ipython/ipython/security/advisories/GHSA-29gw-9793-fvw7>`__.
111
186
112 In addition to fixing this CVE we also fix a couple of outstanding bugs and issues.
187 In addition to fixing this CVE we also fix a couple of outstanding bugs and issues.
113
188
114 As usual you can find the full list of PRs on GitHub under `the 8.10 milestone
189 As usual you can find the full list of PRs on GitHub under `the 8.10 milestone
115 <https://github.com/ipython/ipython/milestone/112?closed=1>`__.
190 <https://github.com/ipython/ipython/milestone/112?closed=1>`__.
116
191
117 In Particular:
192 In Particular:
118
193
119 - bump minimum numpy to `>=1.21` version following NEP29. :ghpull:`13930`
194 - bump minimum numpy to `>=1.21` version following NEP29. :ghpull:`13930`
120 - fix for compatibility with MyPy 1.0. :ghpull:`13933`
195 - fix for compatibility with MyPy 1.0. :ghpull:`13933`
121 - fix nbgrader stalling when IPython's ``showtraceback`` function is
196 - fix nbgrader stalling when IPython's ``showtraceback`` function is
122 monkeypatched. :ghpull:`13934`
197 monkeypatched. :ghpull:`13934`
123
198
124
199
125
200
126 As this release also contains those minimal changes in addition to fixing the
201 As this release also contains those minimal changes in addition to fixing the
127 CVE I decided to bump the minor version anyway.
202 CVE I decided to bump the minor version anyway.
128
203
129 This will not affect the normal release schedule, so IPython 8.11 is due in
204 This will not affect the normal release schedule, so IPython 8.11 is due in
130 about 2 weeks.
205 about 2 weeks.
131
206
132 .. _version 8.9.0:
207 .. _version 8.9.0:
133
208
134 IPython 8.9.0
209 IPython 8.9.0
135 -------------
210 -------------
136
211
137 Second release of IPython in 2023, last Friday of the month, we are back on
212 Second release of IPython in 2023, last Friday of the month, we are back on
138 track. This is a small release with a few bug-fixes, and improvements, mostly
213 track. This is a small release with a few bug-fixes, and improvements, mostly
139 with respect to terminal shortcuts.
214 with respect to terminal shortcuts.
140
215
141
216
142 The biggest improvement for 8.9 is a drastic amelioration of the
217 The biggest improvement for 8.9 is a drastic amelioration of the
143 auto-suggestions sponsored by D.E. Shaw and implemented by the more and more
218 auto-suggestions sponsored by D.E. Shaw and implemented by the more and more
144 active contributor `@krassowski <https://github.com/krassowski>`.
219 active contributor `@krassowski <https://github.com/krassowski>`.
145
220
146 - ``right`` accepts a single character from suggestion
221 - ``right`` accepts a single character from suggestion
147 - ``ctrl+right`` accepts a semantic token (macos default shortcuts take
222 - ``ctrl+right`` accepts a semantic token (macos default shortcuts take
148 precedence and need to be disabled to make this work)
223 precedence and need to be disabled to make this work)
149 - ``backspace`` deletes a character and resumes hinting autosuggestions
224 - ``backspace`` deletes a character and resumes hinting autosuggestions
150 - ``ctrl-left`` accepts suggestion and moves cursor left one character.
225 - ``ctrl-left`` accepts suggestion and moves cursor left one character.
151 - ``backspace`` deletes a character and resumes hinting autosuggestions
226 - ``backspace`` deletes a character and resumes hinting autosuggestions
152 - ``down`` moves to suggestion to later in history when no lines are present below the cursors.
227 - ``down`` moves to suggestion to later in history when no lines are present below the cursors.
153 - ``up`` moves to suggestion from earlier in history when no lines are present above the cursor.
228 - ``up`` moves to suggestion from earlier in history when no lines are present above the cursor.
154
229
155 This is best described by the Gif posted by `@krassowski
230 This is best described by the Gif posted by `@krassowski
156 <https://github.com/krassowski>`, and in the PR itself :ghpull:`13888`.
231 <https://github.com/krassowski>`, and in the PR itself :ghpull:`13888`.
157
232
158 .. image:: ../_images/autosuggest.gif
233 .. image:: ../_images/autosuggest.gif
159
234
160 Please report any feedback in order for us to improve the user experience.
235 Please report any feedback in order for us to improve the user experience.
161 In particular we are also working on making the shortcuts configurable.
236 In particular we are also working on making the shortcuts configurable.
162
237
163 If you are interested in better terminal shortcuts, I also invite you to
238 If you are interested in better terminal shortcuts, I also invite you to
164 participate in issue `13879
239 participate in issue `13879
165 <https://github.com/ipython/ipython/issues/13879>`__.
240 <https://github.com/ipython/ipython/issues/13879>`__.
166
241
167
242
168 As we follow `NEP29
243 As we follow `NEP29
169 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, next version of
244 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__, next version of
170 IPython will officially stop supporting numpy 1.20, and will stop supporting
245 IPython will officially stop supporting numpy 1.20, and will stop supporting
171 Python 3.8 after April release.
246 Python 3.8 after April release.
172
247
173 As usual you can find the full list of PRs on GitHub under `the 8.9 milestone
248 As usual you can find the full list of PRs on GitHub under `the 8.9 milestone
174 <https://github.com/ipython/ipython/milestone/111?closed=1>`__.
249 <https://github.com/ipython/ipython/milestone/111?closed=1>`__.
175
250
176
251
177 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
252 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
178 work on IPython and related libraries.
253 work on IPython and related libraries.
179
254
180 .. _version 8.8.0:
255 .. _version 8.8.0:
181
256
182 IPython 8.8.0
257 IPython 8.8.0
183 -------------
258 -------------
184
259
185 First release of IPython in 2023 as there was no release at the end of
260 First release of IPython in 2023 as there was no release at the end of
186 December.
261 December.
187
262
188 This is an unusually big release (relatively speaking) with more than 15 Pull
263 This is an unusually big release (relatively speaking) with more than 15 Pull
189 Requests merged.
264 Requests merged.
190
265
191 Of particular interest are:
266 Of particular interest are:
192
267
193 - :ghpull:`13852` that replaces the greedy completer and improves
268 - :ghpull:`13852` that replaces the greedy completer and improves
194 completion, in particular for dictionary keys.
269 completion, in particular for dictionary keys.
195 - :ghpull:`13858` that adds ``py.typed`` to ``setup.cfg`` to make sure it is
270 - :ghpull:`13858` that adds ``py.typed`` to ``setup.cfg`` to make sure it is
196 bundled in wheels.
271 bundled in wheels.
197 - :ghpull:`13869` that implements tab completions for IPython options in the
272 - :ghpull:`13869` that implements tab completions for IPython options in the
198 shell when using `argcomplete <https://github.com/kislyuk/argcomplete>`. I
273 shell when using `argcomplete <https://github.com/kislyuk/argcomplete>`. I
199 believe this also needs a recent version of Traitlets.
274 believe this also needs a recent version of Traitlets.
200 - :ghpull:`13865` makes the ``inspector`` class of `InteractiveShell`
275 - :ghpull:`13865` makes the ``inspector`` class of `InteractiveShell`
201 configurable.
276 configurable.
202 - :ghpull:`13880` that removes minor-version entrypoints as the minor version
277 - :ghpull:`13880` that removes minor-version entrypoints as the minor version
203 entry points that would be included in the wheel would be the one of the
278 entry points that would be included in the wheel would be the one of the
204 Python version that was used to build the ``whl`` file.
279 Python version that was used to build the ``whl`` file.
205
280
206 In no particular order, the rest of the changes update the test suite to be
281 In no particular order, the rest of the changes update the test suite to be
207 compatible with Pygments 2.14, various docfixes, testing on more recent python
282 compatible with Pygments 2.14, various docfixes, testing on more recent python
208 versions and various updates.
283 versions and various updates.
209
284
210 As usual you can find the full list of PRs on GitHub under `the 8.8 milestone
285 As usual you can find the full list of PRs on GitHub under `the 8.8 milestone
211 <https://github.com/ipython/ipython/milestone/110>`__.
286 <https://github.com/ipython/ipython/milestone/110>`__.
212
287
213 Many thanks to @krassowski for the many PRs and @jasongrout for reviewing and
288 Many thanks to @krassowski for the many PRs and @jasongrout for reviewing and
214 merging contributions.
289 merging contributions.
215
290
216 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
291 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
217 work on IPython and related libraries.
292 work on IPython and related libraries.
218
293
219 .. _version 8.7.0:
294 .. _version 8.7.0:
220
295
221 IPython 8.7.0
296 IPython 8.7.0
222 -------------
297 -------------
223
298
224
299
225 Small release of IPython with a couple of bug fixes and new features for this
300 Small release of IPython with a couple of bug fixes and new features for this
226 month. Next month is the end of year, it is unclear if there will be a release
301 month. Next month is the end of year, it is unclear if there will be a release
227 close to the new year's eve, or if the next release will be at the end of January.
302 close to the new year's eve, or if the next release will be at the end of January.
228
303
229 Here are a few of the relevant fixes,
304 Here are a few of the relevant fixes,
230 as usual you can find the full list of PRs on GitHub under `the 8.7 milestone
305 as usual you can find the full list of PRs on GitHub under `the 8.7 milestone
231 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.7>`__.
306 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.7>`__.
232
307
233
308
234 - :ghpull:`13834` bump the minimum prompt toolkit to 3.0.11.
309 - :ghpull:`13834` bump the minimum prompt toolkit to 3.0.11.
235 - IPython shipped with the ``py.typed`` marker now, and we are progressively
310 - IPython shipped with the ``py.typed`` marker now, and we are progressively
236 adding more types. :ghpull:`13831`
311 adding more types. :ghpull:`13831`
237 - :ghpull:`13817` add configuration of code blacks formatting.
312 - :ghpull:`13817` add configuration of code blacks formatting.
238
313
239
314
240 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
315 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
241 work on IPython and related libraries.
316 work on IPython and related libraries.
242
317
243
318
244 .. _version 8.6.0:
319 .. _version 8.6.0:
245
320
246 IPython 8.6.0
321 IPython 8.6.0
247 -------------
322 -------------
248
323
249 Back to a more regular release schedule (at least I try), as Friday is
324 Back to a more regular release schedule (at least I try), as Friday is
250 already over by more than 24h hours. This is a slightly bigger release with a
325 already over by more than 24h hours. This is a slightly bigger release with a
251 few new features that contain no less than 25 PRs.
326 few new features that contain no less than 25 PRs.
252
327
253 We'll notably found a couple of non negligible changes:
328 We'll notably found a couple of non negligible changes:
254
329
255 The ``install_ext`` and related functions have been removed after being
330 The ``install_ext`` and related functions have been removed after being
256 deprecated for years. You can use pip to install extensions. ``pip`` did not
331 deprecated for years. You can use pip to install extensions. ``pip`` did not
257 exist when ``install_ext`` was introduced. You can still load local extensions
332 exist when ``install_ext`` was introduced. You can still load local extensions
258 without installing them. Just set your ``sys.path`` for example. :ghpull:`13744`
333 without installing them. Just set your ``sys.path`` for example. :ghpull:`13744`
259
334
260 IPython now has extra entry points that use the major *and minor* version of
335 IPython now has extra entry points that use the major *and minor* version of
261 python. For some of you this means that you can do a quick ``ipython3.10`` to
336 python. For some of you this means that you can do a quick ``ipython3.10`` to
262 launch IPython from the Python 3.10 interpreter, while still using Python 3.11
337 launch IPython from the Python 3.10 interpreter, while still using Python 3.11
263 as your main Python. :ghpull:`13743`
338 as your main Python. :ghpull:`13743`
264
339
265 The completer matcher API has been improved. See :ghpull:`13745`. This should
340 The completer matcher API has been improved. See :ghpull:`13745`. This should
266 improve the type inference and improve dict keys completions in many use case.
341 improve the type inference and improve dict keys completions in many use case.
267 Thanks ``@krassowski`` for all the work, and the D.E. Shaw group for sponsoring
342 Thanks ``@krassowski`` for all the work, and the D.E. Shaw group for sponsoring
268 it.
343 it.
269
344
270 The color of error nodes in tracebacks can now be customized. See
345 The color of error nodes in tracebacks can now be customized. See
271 :ghpull:`13756`. This is a private attribute until someone finds the time to
346 :ghpull:`13756`. This is a private attribute until someone finds the time to
272 properly add a configuration option. Note that with Python 3.11 that also shows
347 properly add a configuration option. Note that with Python 3.11 that also shows
273 the relevant nodes in traceback, it would be good to leverage this information
348 the relevant nodes in traceback, it would be good to leverage this information
274 (plus the "did you mean" info added on attribute errors). But that's likely work
349 (plus the "did you mean" info added on attribute errors). But that's likely work
275 I won't have time to do before long, so contributions welcome.
350 I won't have time to do before long, so contributions welcome.
276
351
277 As we follow NEP 29, we removed support for numpy 1.19 :ghpull:`13760`.
352 As we follow NEP 29, we removed support for numpy 1.19 :ghpull:`13760`.
278
353
279
354
280 The ``open()`` function present in the user namespace by default will now refuse
355 The ``open()`` function present in the user namespace by default will now refuse
281 to open the file descriptors 0,1,2 (stdin, out, err), to avoid crashing IPython.
356 to open the file descriptors 0,1,2 (stdin, out, err), to avoid crashing IPython.
282 This mostly occurs in teaching context when incorrect values get passed around.
357 This mostly occurs in teaching context when incorrect values get passed around.
283
358
284
359
285 The ``?``, ``??``, and corresponding ``pinfo``, ``pinfo2`` magics can now find
360 The ``?``, ``??``, and corresponding ``pinfo``, ``pinfo2`` magics can now find
286 objects inside arrays. That is to say, the following now works::
361 objects inside arrays. That is to say, the following now works::
287
362
288
363
289 >>> def my_func(*arg, **kwargs):pass
364 >>> def my_func(*arg, **kwargs):pass
290 >>> container = [my_func]
365 >>> container = [my_func]
291 >>> container[0]?
366 >>> container[0]?
292
367
293
368
294 If ``container`` define a custom ``getitem``, this __will__ trigger the custom
369 If ``container`` define a custom ``getitem``, this __will__ trigger the custom
295 method. So don't put side effects in your ``getitems``. Thanks to the D.E. Shaw
370 method. So don't put side effects in your ``getitems``. Thanks to the D.E. Shaw
296 group for the request and sponsoring the work.
371 group for the request and sponsoring the work.
297
372
298
373
299 As usual you can find the full list of PRs on GitHub under `the 8.6 milestone
374 As usual you can find the full list of PRs on GitHub under `the 8.6 milestone
300 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.6>`__.
375 <https://github.com/ipython/ipython/pulls?q=milestone%3A8.6>`__.
301
376
302 Thanks to all hacktoberfest contributors, please contribute to
377 Thanks to all hacktoberfest contributors, please contribute to
303 `closember.org <https://closember.org/>`__.
378 `closember.org <https://closember.org/>`__.
304
379
305 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
380 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
306 work on IPython and related libraries.
381 work on IPython and related libraries.
307
382
308 .. _version 8.5.0:
383 .. _version 8.5.0:
309
384
310 IPython 8.5.0
385 IPython 8.5.0
311 -------------
386 -------------
312
387
313 First release since a couple of month due to various reasons and timing preventing
388 First release since a couple of month due to various reasons and timing preventing
314 me for sticking to the usual monthly release the last Friday of each month. This
389 me for sticking to the usual monthly release the last Friday of each month. This
315 is of non negligible size as it has more than two dozen PRs with various fixes
390 is of non negligible size as it has more than two dozen PRs with various fixes
316 an bug fixes.
391 an bug fixes.
317
392
318 Many thanks to everybody who contributed PRs for your patience in review and
393 Many thanks to everybody who contributed PRs for your patience in review and
319 merges.
394 merges.
320
395
321 Here is a non-exhaustive list of changes that have been implemented for IPython
396 Here is a non-exhaustive list of changes that have been implemented for IPython
322 8.5.0. As usual you can find the full list of issues and PRs tagged with `the
397 8.5.0. As usual you can find the full list of issues and PRs tagged with `the
323 8.5 milestone
398 8.5 milestone
324 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A8.5+>`__.
399 <https://github.com/ipython/ipython/pulls?q=is%3Aclosed+milestone%3A8.5+>`__.
325
400
326 - Added a shortcut for accepting auto suggestion. The End key shortcut for
401 - Added a shortcut for accepting auto suggestion. The End key shortcut for
327 accepting auto-suggestion This binding works in Vi mode too, provided
402 accepting auto-suggestion This binding works in Vi mode too, provided
328 ``TerminalInteractiveShell.emacs_bindings_in_vi_insert_mode`` is set to be
403 ``TerminalInteractiveShell.emacs_bindings_in_vi_insert_mode`` is set to be
329 ``True`` :ghpull:`13566`.
404 ``True`` :ghpull:`13566`.
330
405
331 - No popup in window for latex generation when generating latex (e.g. via
406 - No popup in window for latex generation when generating latex (e.g. via
332 `_latex_repr_`) no popup window is shows under Windows. :ghpull:`13679`
407 `_latex_repr_`) no popup window is shows under Windows. :ghpull:`13679`
333
408
334 - Fixed error raised when attempting to tab-complete an input string with
409 - Fixed error raised when attempting to tab-complete an input string with
335 consecutive periods or forward slashes (such as "file:///var/log/...").
410 consecutive periods or forward slashes (such as "file:///var/log/...").
336 :ghpull:`13675`
411 :ghpull:`13675`
337
412
338 - Relative filenames in Latex rendering :
413 - Relative filenames in Latex rendering :
339 The `latex_to_png_dvipng` command internally generates input and output file
414 The `latex_to_png_dvipng` command internally generates input and output file
340 arguments to `latex` and `dvipis`. These arguments are now generated as
415 arguments to `latex` and `dvipis`. These arguments are now generated as
341 relative files to the current working directory instead of absolute file
416 relative files to the current working directory instead of absolute file
342 paths. This solves a problem where the current working directory contains
417 paths. This solves a problem where the current working directory contains
343 characters that are not handled properly by `latex` and `dvips`. There are
418 characters that are not handled properly by `latex` and `dvips`. There are
344 no changes to the user API. :ghpull:`13680`
419 no changes to the user API. :ghpull:`13680`
345
420
346 - Stripping decorators bug: Fixed bug which meant that ipython code blocks in
421 - Stripping decorators bug: Fixed bug which meant that ipython code blocks in
347 restructured text documents executed with the ipython-sphinx extension
422 restructured text documents executed with the ipython-sphinx extension
348 skipped any lines of code containing python decorators. :ghpull:`13612`
423 skipped any lines of code containing python decorators. :ghpull:`13612`
349
424
350 - Allow some modules with frozen dataclasses to be reloaded. :ghpull:`13732`
425 - Allow some modules with frozen dataclasses to be reloaded. :ghpull:`13732`
351 - Fix paste magic on wayland. :ghpull:`13671`
426 - Fix paste magic on wayland. :ghpull:`13671`
352 - show maxlen in deque's repr. :ghpull:`13648`
427 - show maxlen in deque's repr. :ghpull:`13648`
353
428
354 Restore line numbers for Input
429 Restore line numbers for Input
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
430 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
356
431
357 Line number information in tracebacks from input are restored.
432 Line number information in tracebacks from input are restored.
358 Line numbers from input were removed during the transition to v8 enhanced traceback reporting.
433 Line numbers from input were removed during the transition to v8 enhanced traceback reporting.
359
434
360 So, instead of::
435 So, instead of::
361
436
362 ---------------------------------------------------------------------------
437 ---------------------------------------------------------------------------
363 ZeroDivisionError Traceback (most recent call last)
438 ZeroDivisionError Traceback (most recent call last)
364 Input In [3], in <cell line: 1>()
439 Input In [3], in <cell line: 1>()
365 ----> 1 myfunc(2)
440 ----> 1 myfunc(2)
366
441
367 Input In [2], in myfunc(z)
442 Input In [2], in myfunc(z)
368 1 def myfunc(z):
443 1 def myfunc(z):
369 ----> 2 foo.boo(z-1)
444 ----> 2 foo.boo(z-1)
370
445
371 File ~/code/python/ipython/foo.py:3, in boo(x)
446 File ~/code/python/ipython/foo.py:3, in boo(x)
372 2 def boo(x):
447 2 def boo(x):
373 ----> 3 return 1/(1-x)
448 ----> 3 return 1/(1-x)
374
449
375 ZeroDivisionError: division by zero
450 ZeroDivisionError: division by zero
376
451
377 The error traceback now looks like::
452 The error traceback now looks like::
378
453
379 ---------------------------------------------------------------------------
454 ---------------------------------------------------------------------------
380 ZeroDivisionError Traceback (most recent call last)
455 ZeroDivisionError Traceback (most recent call last)
381 Cell In [3], line 1
456 Cell In [3], line 1
382 ----> 1 myfunc(2)
457 ----> 1 myfunc(2)
383
458
384 Cell In [2], line 2, in myfunc(z)
459 Cell In [2], line 2, in myfunc(z)
385 1 def myfunc(z):
460 1 def myfunc(z):
386 ----> 2 foo.boo(z-1)
461 ----> 2 foo.boo(z-1)
387
462
388 File ~/code/python/ipython/foo.py:3, in boo(x)
463 File ~/code/python/ipython/foo.py:3, in boo(x)
389 2 def boo(x):
464 2 def boo(x):
390 ----> 3 return 1/(1-x)
465 ----> 3 return 1/(1-x)
391
466
392 ZeroDivisionError: division by zero
467 ZeroDivisionError: division by zero
393
468
394 or, with xmode=Plain::
469 or, with xmode=Plain::
395
470
396 Traceback (most recent call last):
471 Traceback (most recent call last):
397 Cell In [12], line 1
472 Cell In [12], line 1
398 myfunc(2)
473 myfunc(2)
399 Cell In [6], line 2 in myfunc
474 Cell In [6], line 2 in myfunc
400 foo.boo(z-1)
475 foo.boo(z-1)
401 File ~/code/python/ipython/foo.py:3 in boo
476 File ~/code/python/ipython/foo.py:3 in boo
402 return 1/(1-x)
477 return 1/(1-x)
403 ZeroDivisionError: division by zero
478 ZeroDivisionError: division by zero
404
479
405 :ghpull:`13560`
480 :ghpull:`13560`
406
481
407 New setting to silence warning if working inside a virtual environment
482 New setting to silence warning if working inside a virtual environment
408 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
409
484
410 Previously, when starting IPython in a virtual environment without IPython installed (so IPython from the global environment is used), the following warning was printed:
485 Previously, when starting IPython in a virtual environment without IPython installed (so IPython from the global environment is used), the following warning was printed:
411
486
412 Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
487 Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
413
488
414 This warning can be permanently silenced by setting ``c.InteractiveShell.warn_venv`` to ``False`` (the default is ``True``).
489 This warning can be permanently silenced by setting ``c.InteractiveShell.warn_venv`` to ``False`` (the default is ``True``).
415
490
416 :ghpull:`13706`
491 :ghpull:`13706`
417
492
418 -------
493 -------
419
494
420 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
495 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
421 work on IPython and related libraries.
496 work on IPython and related libraries.
422
497
423
498
424 .. _version 8.4.0:
499 .. _version 8.4.0:
425
500
426 IPython 8.4.0
501 IPython 8.4.0
427 -------------
502 -------------
428
503
429 As for 7.34, this version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
504 As for 7.34, this version contains a single fix: fix uncaught BdbQuit exceptions on ipdb
430 exit :ghpull:`13668`, and a single typo fix in documentation: :ghpull:`13682`
505 exit :ghpull:`13668`, and a single typo fix in documentation: :ghpull:`13682`
431
506
432 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
507 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
433 work on IPython and related libraries.
508 work on IPython and related libraries.
434
509
435
510
436 .. _version 8.3.0:
511 .. _version 8.3.0:
437
512
438 IPython 8.3.0
513 IPython 8.3.0
439 -------------
514 -------------
440
515
441 - :ghpull:`13625`, using ``?``, ``??``, ``*?`` will not call
516 - :ghpull:`13625`, using ``?``, ``??``, ``*?`` will not call
442 ``set_next_input`` as most frontend allow proper multiline editing and it was
517 ``set_next_input`` as most frontend allow proper multiline editing and it was
443 causing issues for many users of multi-cell frontends. This has been backported to 7.33
518 causing issues for many users of multi-cell frontends. This has been backported to 7.33
444
519
445
520
446 - :ghpull:`13600`, ``pre_run_*``-hooks will now have a ``cell_id`` attribute on
521 - :ghpull:`13600`, ``pre_run_*``-hooks will now have a ``cell_id`` attribute on
447 the info object when frontend provides it. This has been backported to 7.33
522 the info object when frontend provides it. This has been backported to 7.33
448
523
449 - :ghpull:`13624`, fixed :kbd:`End` key being broken after accepting an
524 - :ghpull:`13624`, fixed :kbd:`End` key being broken after accepting an
450 auto-suggestion.
525 auto-suggestion.
451
526
452 - :ghpull:`13657` fixed an issue where history from different sessions would be mixed.
527 - :ghpull:`13657` fixed an issue where history from different sessions would be mixed.
453
528
454 .. _version 8.2.0:
529 .. _version 8.2.0:
455
530
456 IPython 8.2.0
531 IPython 8.2.0
457 -------------
532 -------------
458
533
459 IPython 8.2 mostly bring bugfixes to IPython.
534 IPython 8.2 mostly bring bugfixes to IPython.
460
535
461 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
536 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
462 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
537 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
463 - History is now pulled from the sqitel database and not from in-memory.
538 - History is now pulled from the sqitel database and not from in-memory.
464 In particular when using the ``%paste`` magic, the content of the pasted text will
539 In particular when using the ``%paste`` magic, the content of the pasted text will
465 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
540 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
466 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
541 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
467 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
542 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
468
543
469
544
470 I am still trying to fix and investigate :ghissue:`13598`, which seems to be
545 I am still trying to fix and investigate :ghissue:`13598`, which seems to be
471 random, and would appreciate help if you find a reproducible minimal case. I've
546 random, and would appreciate help if you find a reproducible minimal case. I've
472 tried to make various changes to the codebase to mitigate it, but a proper fix
547 tried to make various changes to the codebase to mitigate it, but a proper fix
473 will be difficult without understanding the cause.
548 will be difficult without understanding the cause.
474
549
475
550
476 All the issues on pull-requests for this release can be found in the `8.2
551 All the issues on pull-requests for this release can be found in the `8.2
477 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
552 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
478 documentation only PR can be found as part of the `7.33 milestone
553 documentation only PR can be found as part of the `7.33 milestone
479 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
554 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
480
555
481 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
556 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
482 work on IPython and related libraries.
557 work on IPython and related libraries.
483
558
484 .. _version 8.1.1:
559 .. _version 8.1.1:
485
560
486 IPython 8.1.1
561 IPython 8.1.1
487 -------------
562 -------------
488
563
489 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
564 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
490
565
491 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
566 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
492 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
567 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
493
568
494 .. _version 8.1:
569 .. _version 8.1:
495
570
496 IPython 8.1.0
571 IPython 8.1.0
497 -------------
572 -------------
498
573
499 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
574 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
500 updates a few behaviors that were problematic with the 8.0 as with many new major
575 updates a few behaviors that were problematic with the 8.0 as with many new major
501 release.
576 release.
502
577
503 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
578 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
504 features listed in :ref:`version 7.32`.
579 features listed in :ref:`version 7.32`.
505
580
506 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
581 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
507 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
582 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
508 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
583 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
509 is now explicit in ``setup.cfg``/``setup.py``
584 is now explicit in ``setup.cfg``/``setup.py``
510 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
585 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
511 - Multi-line edit executes too early with await. :ghpull:`13424`
586 - Multi-line edit executes too early with await. :ghpull:`13424`
512
587
513 - ``black`` is back as an optional dependency, and autoformatting disabled by
588 - ``black`` is back as an optional dependency, and autoformatting disabled by
514 default until some fixes are implemented (black improperly reformat magics).
589 default until some fixes are implemented (black improperly reformat magics).
515 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
590 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
516 reformatter has been added :ghpull:`13528` . You can use
591 reformatter has been added :ghpull:`13528` . You can use
517 ``TerminalInteractiveShell.autoformatter="black"``,
592 ``TerminalInteractiveShell.autoformatter="black"``,
518 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formating
593 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formating
519 with black, or switch to yapf.
594 with black, or switch to yapf.
520
595
521 - Fix and issue where ``display`` was not defined.
596 - Fix and issue where ``display`` was not defined.
522
597
523 - Auto suggestions are now configurable. Currently only
598 - Auto suggestions are now configurable. Currently only
524 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
599 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
525 welcomed. :ghpull:`13475`
600 welcomed. :ghpull:`13475`
526
601
527 - multiple packaging/testing improvement to simplify downstream packaging
602 - multiple packaging/testing improvement to simplify downstream packaging
528 (xfail with reasons, try to not access network...).
603 (xfail with reasons, try to not access network...).
529
604
530 - Update deprecation. ``InteractiveShell.magic`` internal method has been
605 - Update deprecation. ``InteractiveShell.magic`` internal method has been
531 deprecated for many years but did not emit a warning until now.
606 deprecated for many years but did not emit a warning until now.
532
607
533 - internal ``appended_to_syspath`` context manager has been deprecated.
608 - internal ``appended_to_syspath`` context manager has been deprecated.
534
609
535 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
610 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
536
611
537 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
612 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
538
613
539 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
614 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
540
615
541 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
616 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
542 removed.
617 removed.
543
618
544 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
619 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
545
620
546
621
547 We want to remind users that IPython is part of the Jupyter organisations, and
622 We want to remind users that IPython is part of the Jupyter organisations, and
548 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
623 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
549 Abuse and non-respectful comments on discussion will not be tolerated.
624 Abuse and non-respectful comments on discussion will not be tolerated.
550
625
551 Many thanks to all the contributors to this release, many of the above fixed issues and
626 Many thanks to all the contributors to this release, many of the above fixed issues and
552 new features were done by first time contributors, showing there is still
627 new features were done by first time contributors, showing there is still
553 plenty of easy contribution possible in IPython
628 plenty of easy contribution possible in IPython
554 . You can find all individual contributions
629 . You can find all individual contributions
555 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
630 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
556
631
557 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
632 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
558 work on IPython and related libraries. In particular the Lazy autoloading of
633 work on IPython and related libraries. In particular the Lazy autoloading of
559 magics that you will find described in the 7.32 release notes.
634 magics that you will find described in the 7.32 release notes.
560
635
561
636
562 .. _version 8.0.1:
637 .. _version 8.0.1:
563
638
564 IPython 8.0.1 (CVE-2022-21699)
639 IPython 8.0.1 (CVE-2022-21699)
565 ------------------------------
640 ------------------------------
566
641
567 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
642 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
568 values in order to prevent potential Execution with Unnecessary Privileges.
643 values in order to prevent potential Execution with Unnecessary Privileges.
569
644
570 Almost all version of IPython looks for configuration and profiles in current
645 Almost all version of IPython looks for configuration and profiles in current
571 working directory. Since IPython was developed before pip and environments
646 working directory. Since IPython was developed before pip and environments
572 existed it was used a convenient way to load code/packages in a project
647 existed it was used a convenient way to load code/packages in a project
573 dependant way.
648 dependant way.
574
649
575 In 2022, it is not necessary anymore, and can lead to confusing behavior where
650 In 2022, it is not necessary anymore, and can lead to confusing behavior where
576 for example cloning a repository and starting IPython or loading a notebook from
651 for example cloning a repository and starting IPython or loading a notebook from
577 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
652 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
578 code execution.
653 code execution.
579
654
580
655
581 I did not find any standard way for packaged to advertise CVEs they fix, I'm
656 I did not find any standard way for packaged to advertise CVEs they fix, I'm
582 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
657 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
583 list the CVEs that should have been fixed. This attribute is informational only
658 list the CVEs that should have been fixed. This attribute is informational only
584 as if a executable has a flaw, this value can always be changed by an attacker.
659 as if a executable has a flaw, this value can always be changed by an attacker.
585
660
586 .. code::
661 .. code::
587
662
588 In [1]: import IPython
663 In [1]: import IPython
589
664
590 In [2]: IPython.__patched_cves__
665 In [2]: IPython.__patched_cves__
591 Out[2]: {'CVE-2022-21699'}
666 Out[2]: {'CVE-2022-21699'}
592
667
593 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
668 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
594 Out[3]: True
669 Out[3]: True
595
670
596 Thus starting with this version:
671 Thus starting with this version:
597
672
598 - The current working directory is not searched anymore for profiles or
673 - The current working directory is not searched anymore for profiles or
599 configurations files.
674 configurations files.
600 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
675 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
601 the list of fixed CVE. This is informational only.
676 the list of fixed CVE. This is informational only.
602
677
603 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
678 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
604
679
605
680
606 .. _version 8.0:
681 .. _version 8.0:
607
682
608 IPython 8.0
683 IPython 8.0
609 -----------
684 -----------
610
685
611 IPython 8.0 is bringing a large number of new features and improvements to both the
686 IPython 8.0 is bringing a large number of new features and improvements to both the
612 user of the terminal and of the kernel via Jupyter. The removal of compatibility
687 user of the terminal and of the kernel via Jupyter. The removal of compatibility
613 with an older version of Python is also the opportunity to do a couple of
688 with an older version of Python is also the opportunity to do a couple of
614 performance improvements in particular with respect to startup time.
689 performance improvements in particular with respect to startup time.
615 The 8.x branch started diverging from its predecessor around IPython 7.12
690 The 8.x branch started diverging from its predecessor around IPython 7.12
616 (January 2020).
691 (January 2020).
617
692
618 This release contains 250+ pull requests, in addition to many of the features
693 This release contains 250+ pull requests, in addition to many of the features
619 and backports that have made it to the 7.x branch. Please see the
694 and backports that have made it to the 7.x branch. Please see the
620 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
695 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
621
696
622 Please feel free to send pull requests to update those notes after release,
697 Please feel free to send pull requests to update those notes after release,
623 I have likely forgotten a few things reviewing 250+ PRs.
698 I have likely forgotten a few things reviewing 250+ PRs.
624
699
625 Dependencies changes/downstream packaging
700 Dependencies changes/downstream packaging
626 -----------------------------------------
701 -----------------------------------------
627
702
628 Most of our building steps have been changed to be (mostly) declarative
703 Most of our building steps have been changed to be (mostly) declarative
629 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
704 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
630 looking for help to do so.
705 looking for help to do so.
631
706
632 - minimum supported ``traitlets`` version is now 5+
707 - minimum supported ``traitlets`` version is now 5+
633 - we now require ``stack_data``
708 - we now require ``stack_data``
634 - minimal Python is now 3.8
709 - minimal Python is now 3.8
635 - ``nose`` is not a testing requirement anymore
710 - ``nose`` is not a testing requirement anymore
636 - ``pytest`` replaces nose.
711 - ``pytest`` replaces nose.
637 - ``iptest``/``iptest3`` cli entrypoints do not exist anymore.
712 - ``iptest``/``iptest3`` cli entrypoints do not exist anymore.
638 - the minimum officially ​supported ``numpy`` version has been bumped, but this should
713 - the minimum officially ​supported ``numpy`` version has been bumped, but this should
639 not have much effect on packaging.
714 not have much effect on packaging.
640
715
641
716
642 Deprecation and removal
717 Deprecation and removal
643 -----------------------
718 -----------------------
644
719
645 We removed almost all features, arguments, functions, and modules that were
720 We removed almost all features, arguments, functions, and modules that were
646 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
721 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
647 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
722 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
648 The few remaining deprecated features we left have better deprecation warnings
723 The few remaining deprecated features we left have better deprecation warnings
649 or have been turned into explicit errors for better error messages.
724 or have been turned into explicit errors for better error messages.
650
725
651 I will use this occasion to add the following requests to anyone emitting a
726 I will use this occasion to add the following requests to anyone emitting a
652 deprecation warning:
727 deprecation warning:
653
728
654 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
729 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
655 caller context, and not the callee one.
730 caller context, and not the callee one.
656 - Please add **since which version** something is deprecated.
731 - Please add **since which version** something is deprecated.
657
732
658 As a side note, it is much easier to conditionally compare version
733 As a side note, it is much easier to conditionally compare version
659 numbers rather than using ``try/except`` when functionality changes with a version.
734 numbers rather than using ``try/except`` when functionality changes with a version.
660
735
661 I won't list all the removed features here, but modules like ``IPython.kernel``,
736 I won't list all the removed features here, but modules like ``IPython.kernel``,
662 which was just a shim module around ``ipykernel`` for the past 8 years, have been
737 which was just a shim module around ``ipykernel`` for the past 8 years, have been
663 removed, and so many other similar things that pre-date the name **Jupyter**
738 removed, and so many other similar things that pre-date the name **Jupyter**
664 itself.
739 itself.
665
740
666 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
741 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
667 handled by ``load_extension``.
742 handled by ``load_extension``.
668
743
669 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
744 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
670 other packages and no longer need to be inside IPython.
745 other packages and no longer need to be inside IPython.
671
746
672
747
673 Documentation
748 Documentation
674 -------------
749 -------------
675
750
676 The majority of our docstrings have now been reformatted and automatically fixed by
751 The majority of our docstrings have now been reformatted and automatically fixed by
677 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
752 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
678 to numpydoc.
753 to numpydoc.
679
754
680 Type annotations
755 Type annotations
681 ----------------
756 ----------------
682
757
683 While IPython itself is highly dynamic and can't be completely typed, many of
758 While IPython itself is highly dynamic and can't be completely typed, many of
684 the functions now have type annotations, and part of the codebase is now checked
759 the functions now have type annotations, and part of the codebase is now checked
685 by mypy.
760 by mypy.
686
761
687
762
688 Featured changes
763 Featured changes
689 ----------------
764 ----------------
690
765
691 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
766 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
692 Please note as well that many features have been added in the 7.x branch as well
767 Please note as well that many features have been added in the 7.x branch as well
693 (and hence why you want to read the 7.x what's new notes), in particular
768 (and hence why you want to read the 7.x what's new notes), in particular
694 features contributed by QuantStack (with respect to debugger protocol and Xeus
769 features contributed by QuantStack (with respect to debugger protocol and Xeus
695 Python), as well as many debugger features that I was pleased to implement as
770 Python), as well as many debugger features that I was pleased to implement as
696 part of my work at QuanSight and sponsored by DE Shaw.
771 part of my work at QuanSight and sponsored by DE Shaw.
697
772
698 Traceback improvements
773 Traceback improvements
699 ~~~~~~~~~~~~~~~~~~~~~~
774 ~~~~~~~~~~~~~~~~~~~~~~
700
775
701 Previously, error tracebacks for errors happening in code cells were showing a
776 Previously, error tracebacks for errors happening in code cells were showing a
702 hash, the one used for compiling the Python AST::
777 hash, the one used for compiling the Python AST::
703
778
704 In [1]: def foo():
779 In [1]: def foo():
705 ...: return 3 / 0
780 ...: return 3 / 0
706 ...:
781 ...:
707
782
708 In [2]: foo()
783 In [2]: foo()
709 ---------------------------------------------------------------------------
784 ---------------------------------------------------------------------------
710 ZeroDivisionError Traceback (most recent call last)
785 ZeroDivisionError Traceback (most recent call last)
711 <ipython-input-2-c19b6d9633cf> in <module>
786 <ipython-input-2-c19b6d9633cf> in <module>
712 ----> 1 foo()
787 ----> 1 foo()
713
788
714 <ipython-input-1-1595a74c32d5> in foo()
789 <ipython-input-1-1595a74c32d5> in foo()
715 1 def foo():
790 1 def foo():
716 ----> 2 return 3 / 0
791 ----> 2 return 3 / 0
717 3
792 3
718
793
719 ZeroDivisionError: division by zero
794 ZeroDivisionError: division by zero
720
795
721 The error traceback is now correctly formatted, showing the cell number in which the error happened::
796 The error traceback is now correctly formatted, showing the cell number in which the error happened::
722
797
723 In [1]: def foo():
798 In [1]: def foo():
724 ...: return 3 / 0
799 ...: return 3 / 0
725 ...:
800 ...:
726
801
727 Input In [2]: foo()
802 Input In [2]: foo()
728 ---------------------------------------------------------------------------
803 ---------------------------------------------------------------------------
729 ZeroDivisionError Traceback (most recent call last)
804 ZeroDivisionError Traceback (most recent call last)
730 input In [2], in <module>
805 input In [2], in <module>
731 ----> 1 foo()
806 ----> 1 foo()
732
807
733 Input In [1], in foo()
808 Input In [1], in foo()
734 1 def foo():
809 1 def foo():
735 ----> 2 return 3 / 0
810 ----> 2 return 3 / 0
736
811
737 ZeroDivisionError: division by zero
812 ZeroDivisionError: division by zero
738
813
739 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
814 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
740 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
815 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
741
816
742 For example in the following snippet::
817 For example in the following snippet::
743
818
744 def foo(i):
819 def foo(i):
745 x = [[[0]]]
820 x = [[[0]]]
746 return x[0][i][0]
821 return x[0][i][0]
747
822
748
823
749 def bar():
824 def bar():
750 return foo(0) + foo(
825 return foo(0) + foo(
751 1
826 1
752 ) + foo(2)
827 ) + foo(2)
753
828
754
829
755 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
830 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
756 and IPython 8.0 is capable of telling you where the index error occurs::
831 and IPython 8.0 is capable of telling you where the index error occurs::
757
832
758
833
759 IndexError
834 IndexError
760 Input In [2], in <module>
835 Input In [2], in <module>
761 ----> 1 bar()
836 ----> 1 bar()
762 ^^^^^
837 ^^^^^
763
838
764 Input In [1], in bar()
839 Input In [1], in bar()
765 6 def bar():
840 6 def bar():
766 ----> 7 return foo(0) + foo(
841 ----> 7 return foo(0) + foo(
767 ^^^^
842 ^^^^
768 8 1
843 8 1
769 ^^^^^^^^
844 ^^^^^^^^
770 9 ) + foo(2)
845 9 ) + foo(2)
771 ^^^^
846 ^^^^
772
847
773 Input In [1], in foo(i)
848 Input In [1], in foo(i)
774 1 def foo(i):
849 1 def foo(i):
775 2 x = [[[0]]]
850 2 x = [[[0]]]
776 ----> 3 return x[0][i][0]
851 ----> 3 return x[0][i][0]
777 ^^^^^^^
852 ^^^^^^^
778
853
779 The corresponding locations marked here with ``^`` will show up highlighted in
854 The corresponding locations marked here with ``^`` will show up highlighted in
780 the terminal and notebooks.
855 the terminal and notebooks.
781
856
782 Finally, a colon ``::`` and line number is appended after a filename in
857 Finally, a colon ``::`` and line number is appended after a filename in
783 traceback::
858 traceback::
784
859
785
860
786 ZeroDivisionError Traceback (most recent call last)
861 ZeroDivisionError Traceback (most recent call last)
787 File ~/error.py:4, in <module>
862 File ~/error.py:4, in <module>
788 1 def f():
863 1 def f():
789 2 1/0
864 2 1/0
790 ----> 4 f()
865 ----> 4 f()
791
866
792 File ~/error.py:2, in f()
867 File ~/error.py:2, in f()
793 1 def f():
868 1 def f():
794 ----> 2 1/0
869 ----> 2 1/0
795
870
796 Many terminals and editors have integrations enabling you to directly jump to the
871 Many terminals and editors have integrations enabling you to directly jump to the
797 relevant file/line when this syntax is used, so this small addition may have a high
872 relevant file/line when this syntax is used, so this small addition may have a high
798 impact on productivity.
873 impact on productivity.
799
874
800
875
801 Autosuggestions
876 Autosuggestions
802 ~~~~~~~~~~~~~~~
877 ~~~~~~~~~~~~~~~
803
878
804 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>`__.
879 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>`__.
805
880
806 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
881 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
807 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
882 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
808
883
809 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
884 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
810 or right arrow as described below.
885 or right arrow as described below.
811
886
812 1. Start ipython
887 1. Start ipython
813
888
814 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
889 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
815
890
816 2. Run ``print("hello")``
891 2. Run ``print("hello")``
817
892
818 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
893 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
819
894
820 3. start typing ``print`` again to see the autosuggestion
895 3. start typing ``print`` again to see the autosuggestion
821
896
822 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
897 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
823
898
824 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
899 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
825
900
826 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
901 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
827
902
828 You can also complete word by word:
903 You can also complete word by word:
829
904
830 1. Run ``def say_hello(): print("hello")``
905 1. Run ``def say_hello(): print("hello")``
831
906
832 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
907 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
833
908
834 2. Start typing the first letter if ``def`` to see the autosuggestion
909 2. Start typing the first letter if ``def`` to see the autosuggestion
835
910
836 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
911 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
837
912
838 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
913 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
839
914
840 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
915 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
841
916
842 Importantly, this feature does not interfere with tab completion:
917 Importantly, this feature does not interfere with tab completion:
843
918
844 1. After running ``def say_hello(): print("hello")``, press d
919 1. After running ``def say_hello(): print("hello")``, press d
845
920
846 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
921 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
847
922
848 2. Press Tab to start tab completion
923 2. Press Tab to start tab completion
849
924
850 .. image:: ../_images/8.0/auto_suggest_d_completions.png
925 .. image:: ../_images/8.0/auto_suggest_d_completions.png
851
926
852 3A. Press Tab again to select the first option
927 3A. Press Tab again to select the first option
853
928
854 .. image:: ../_images/8.0/auto_suggest_def_completions.png
929 .. image:: ../_images/8.0/auto_suggest_def_completions.png
855
930
856 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
931 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
857
932
858 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
933 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
859
934
860 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
935 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
861
936
862 .. image:: ../_images/8.0/auto_suggest_match_parens.png
937 .. image:: ../_images/8.0/auto_suggest_match_parens.png
863
938
864
939
865 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
940 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
866
941
867 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
942 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
868 - 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/>`__.
943 - 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/>`__.
869
944
870
945
871 Show pinfo information in ipdb using "?" and "??"
946 Show pinfo information in ipdb using "?" and "??"
872 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
873
948
874 In IPDB, it is now possible to show the information about an object using "?"
949 In IPDB, it is now possible to show the information about an object using "?"
875 and "??", in much the same way that it can be done when using the IPython prompt::
950 and "??", in much the same way that it can be done when using the IPython prompt::
876
951
877 ipdb> partial?
952 ipdb> partial?
878 Init signature: partial(self, /, *args, **kwargs)
953 Init signature: partial(self, /, *args, **kwargs)
879 Docstring:
954 Docstring:
880 partial(func, *args, **keywords) - new function with partial application
955 partial(func, *args, **keywords) - new function with partial application
881 of the given arguments and keywords.
956 of the given arguments and keywords.
882 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
957 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
883 Type: type
958 Type: type
884 Subclasses:
959 Subclasses:
885
960
886 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
961 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
887
962
888
963
889 Autoreload 3 feature
964 Autoreload 3 feature
890 ~~~~~~~~~~~~~~~~~~~~
965 ~~~~~~~~~~~~~~~~~~~~
891
966
892 Example: When an IPython session is run with the 'autoreload' extension loaded,
967 Example: When an IPython session is run with the 'autoreload' extension loaded,
893 you will now have the option '3' to select, which means the following:
968 you will now have the option '3' to select, which means the following:
894
969
895 1. replicate all functionality from option 2
970 1. replicate all functionality from option 2
896 2. autoload all new funcs/classes/enums/globals from the module when they are added
971 2. autoload all new funcs/classes/enums/globals from the module when they are added
897 3. autoload all newly imported funcs/classes/enums/globals from external modules
972 3. autoload all newly imported funcs/classes/enums/globals from external modules
898
973
899 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
974 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
900
975
901 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
976 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
902
977
903 Auto formatting with black in the CLI
978 Auto formatting with black in the CLI
904 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
979 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
905
980
906 This feature was present in 7.x, but disabled by default.
981 This feature was present in 7.x, but disabled by default.
907
982
908 In 8.0, input was automatically reformatted with Black when black was installed.
983 In 8.0, input was automatically reformatted with Black when black was installed.
909 This feature has been reverted for the time being.
984 This feature has been reverted for the time being.
910 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
985 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
911
986
912 History Range Glob feature
987 History Range Glob feature
913 ~~~~~~~~~~~~~~~~~~~~~~~~~~
988 ~~~~~~~~~~~~~~~~~~~~~~~~~~
914
989
915 Previously, when using ``%history``, users could specify either
990 Previously, when using ``%history``, users could specify either
916 a range of sessions and lines, for example:
991 a range of sessions and lines, for example:
917
992
918 .. code-block:: python
993 .. code-block:: python
919
994
920 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
995 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
921 # to the fifth line of 6 sessions ago.``
996 # to the fifth line of 6 sessions ago.``
922
997
923 Or users could specify a glob pattern:
998 Or users could specify a glob pattern:
924
999
925 .. code-block:: python
1000 .. code-block:: python
926
1001
927 -g <pattern> # glob ALL history for the specified pattern.
1002 -g <pattern> # glob ALL history for the specified pattern.
928
1003
929 However users could *not* specify both.
1004 However users could *not* specify both.
930
1005
931 If a user *did* specify both a range and a glob pattern,
1006 If a user *did* specify both a range and a glob pattern,
932 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
1007 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
933
1008
934 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.
1009 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.
935
1010
936 Don't start a multi-line cell with sunken parenthesis
1011 Don't start a multi-line cell with sunken parenthesis
937 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
938
1013
939 From now on, IPython will not ask for the next line of input when given a single
1014 From now on, IPython will not ask for the next line of input when given a single
940 line with more closing than opening brackets. For example, this means that if
1015 line with more closing than opening brackets. For example, this means that if
941 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
1016 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
942 the ``...:`` prompt continuation.
1017 the ``...:`` prompt continuation.
943
1018
944 IPython shell for ipdb interact
1019 IPython shell for ipdb interact
945 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1020 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
946
1021
947 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
1022 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
948
1023
949 Automatic Vi prompt stripping
1024 Automatic Vi prompt stripping
950 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1025 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
951
1026
952 When pasting code into IPython, it will strip the leading prompt characters if
1027 When pasting code into IPython, it will strip the leading prompt characters if
953 there are any. For example, you can paste the following code into the console -
1028 there are any. For example, you can paste the following code into the console -
954 it will still work, even though each line is prefixed with prompts (``In``,
1029 it will still work, even though each line is prefixed with prompts (``In``,
955 ``Out``)::
1030 ``Out``)::
956
1031
957 In [1]: 2 * 2 == 4
1032 In [1]: 2 * 2 == 4
958 Out[1]: True
1033 Out[1]: True
959
1034
960 In [2]: print("This still works as pasted")
1035 In [2]: print("This still works as pasted")
961
1036
962
1037
963 Previously, this was not the case for the Vi-mode prompts::
1038 Previously, this was not the case for the Vi-mode prompts::
964
1039
965 In [1]: [ins] In [13]: 2 * 2 == 4
1040 In [1]: [ins] In [13]: 2 * 2 == 4
966 ...: Out[13]: True
1041 ...: Out[13]: True
967 ...:
1042 ...:
968 File "<ipython-input-1-727bb88eaf33>", line 1
1043 File "<ipython-input-1-727bb88eaf33>", line 1
969 [ins] In [13]: 2 * 2 == 4
1044 [ins] In [13]: 2 * 2 == 4
970 ^
1045 ^
971 SyntaxError: invalid syntax
1046 SyntaxError: invalid syntax
972
1047
973 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
1048 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
974 skipped just as the normal ``In`` would be.
1049 skipped just as the normal ``In`` would be.
975
1050
976 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
1051 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
977 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
1052 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
978
1053
979 Empty History Ranges
1054 Empty History Ranges
980 ~~~~~~~~~~~~~~~~~~~~
1055 ~~~~~~~~~~~~~~~~~~~~
981
1056
982 A number of magics that take history ranges can now be used with an empty
1057 A number of magics that take history ranges can now be used with an empty
983 range. These magics are:
1058 range. These magics are:
984
1059
985 * ``%save``
1060 * ``%save``
986 * ``%load``
1061 * ``%load``
987 * ``%pastebin``
1062 * ``%pastebin``
988 * ``%pycat``
1063 * ``%pycat``
989
1064
990 Using them this way will make them take the history of the current session up
1065 Using them this way will make them take the history of the current session up
991 to the point of the magic call (such that the magic itself will not be
1066 to the point of the magic call (such that the magic itself will not be
992 included).
1067 included).
993
1068
994 Therefore it is now possible to save the whole history to a file using
1069 Therefore it is now possible to save the whole history to a file using
995 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
1070 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
996 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
1071 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
997 ``%pastebin``, or view the whole thing syntax-highlighted with a single
1072 ``%pastebin``, or view the whole thing syntax-highlighted with a single
998 ``%pycat``.
1073 ``%pycat``.
999
1074
1000
1075
1001 Windows timing implementation: Switch to process_time
1076 Windows timing implementation: Switch to process_time
1002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1077 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
1078 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
1004 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
1079 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
1005 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
1080 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
1006
1081
1007 Miscellaneous
1082 Miscellaneous
1008 ~~~~~~~~~~~~~
1083 ~~~~~~~~~~~~~
1009 - Non-text formatters are not disabled in the terminal, which should simplify
1084 - Non-text formatters are not disabled in the terminal, which should simplify
1010 writing extensions displaying images or other mimetypes in supporting terminals.
1085 writing extensions displaying images or other mimetypes in supporting terminals.
1011 :ghpull:`12315`
1086 :ghpull:`12315`
1012 - It is now possible to automatically insert matching brackets in Terminal IPython using the
1087 - It is now possible to automatically insert matching brackets in Terminal IPython using the
1013 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
1088 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
1014 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
1089 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
1015 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
1090 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
1016 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
1091 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
1017 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
1092 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
1018 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
1093 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
1019 - The debugger now has a persistent history, which should make it less
1094 - The debugger now has a persistent history, which should make it less
1020 annoying to retype commands :ghpull:`13246`
1095 annoying to retype commands :ghpull:`13246`
1021 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
1096 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
1022 now warn users if they use one of those commands. :ghpull:`12954`
1097 now warn users if they use one of those commands. :ghpull:`12954`
1023 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
1098 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
1024
1099
1025 Re-added support for XDG config directories
1100 Re-added support for XDG config directories
1026 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1101 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1027
1102
1028 XDG support through the years comes and goes. There is a tension between having
1103 XDG support through the years comes and goes. There is a tension between having
1029 an identical location for configuration in all platforms versus having simple instructions.
1104 an identical location for configuration in all platforms versus having simple instructions.
1030 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
1105 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
1031 config files back into ``~/.ipython``. That migration code has now been removed.
1106 config files back into ``~/.ipython``. That migration code has now been removed.
1032 IPython now checks the XDG locations, so if you _manually_ move your config
1107 IPython now checks the XDG locations, so if you _manually_ move your config
1033 files to your preferred location, IPython will not move them back.
1108 files to your preferred location, IPython will not move them back.
1034
1109
1035
1110
1036 Preparing for Python 3.10
1111 Preparing for Python 3.10
1037 -------------------------
1112 -------------------------
1038
1113
1039 To prepare for Python 3.10, we have started working on removing reliance and
1114 To prepare for Python 3.10, we have started working on removing reliance and
1040 any dependency that is not compatible with Python 3.10. This includes migrating our
1115 any dependency that is not compatible with Python 3.10. This includes migrating our
1041 test suite to pytest and starting to remove nose. This also means that the
1116 test suite to pytest and starting to remove nose. This also means that the
1042 ``iptest`` command is now gone and all testing is via pytest.
1117 ``iptest`` command is now gone and all testing is via pytest.
1043
1118
1044 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
1119 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
1045 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
1120 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
1046 who did a fantastic job at updating our code base, migrating to pytest, pushing
1121 who did a fantastic job at updating our code base, migrating to pytest, pushing
1047 our coverage, and fixing a large number of bugs. I highly recommend contacting
1122 our coverage, and fixing a large number of bugs. I highly recommend contacting
1048 them if you need help with C++ and Python projects.
1123 them if you need help with C++ and Python projects.
1049
1124
1050 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+>`__
1125 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+>`__
1051
1126
1052 Removing support for older Python versions
1127 Removing support for older Python versions
1053 ------------------------------------------
1128 ------------------------------------------
1054
1129
1055
1130
1056 We are removing support for Python up through 3.7, allowing internal code to use the more
1131 We are removing support for Python up through 3.7, allowing internal code to use the more
1057 efficient ``pathlib`` and to make better use of type annotations.
1132 efficient ``pathlib`` and to make better use of type annotations.
1058
1133
1059 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
1134 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
1060 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
1135 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
1061
1136
1062
1137
1063 We had about 34 PRs only to update some logic to update some functions from managing strings to
1138 We had about 34 PRs only to update some logic to update some functions from managing strings to
1064 using Pathlib.
1139 using Pathlib.
1065
1140
1066 The completer has also seen significant updates and now makes use of newer Jedi APIs,
1141 The completer has also seen significant updates and now makes use of newer Jedi APIs,
1067 offering faster and more reliable tab completion.
1142 offering faster and more reliable tab completion.
1068
1143
1069 Misc Statistics
1144 Misc Statistics
1070 ---------------
1145 ---------------
1071
1146
1072 Here are some numbers::
1147 Here are some numbers::
1073
1148
1074 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
1149 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
1075 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
1150 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
1076
1151
1077 $ git diff --stat 7.x...master | tail -1
1152 $ git diff --stat 7.x...master | tail -1
1078 340 files changed, 13399 insertions(+), 12421 deletions(-)
1153 340 files changed, 13399 insertions(+), 12421 deletions(-)
1079
1154
1080 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
1155 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
1081 maintainers pushing buttons).::
1156 maintainers pushing buttons).::
1082
1157
1083 $ git shortlog -s --no-merges 7.x...master | sort -nr
1158 $ git shortlog -s --no-merges 7.x...master | sort -nr
1084 535 Matthias Bussonnier
1159 535 Matthias Bussonnier
1085 86 Nikita Kniazev
1160 86 Nikita Kniazev
1086 69 Blazej Michalik
1161 69 Blazej Michalik
1087 49 Samuel Gaist
1162 49 Samuel Gaist
1088 27 Itamar Turner-Trauring
1163 27 Itamar Turner-Trauring
1089 18 Spas Kalaydzhisyki
1164 18 Spas Kalaydzhisyki
1090 17 Thomas Kluyver
1165 17 Thomas Kluyver
1091 17 Quentin Peter
1166 17 Quentin Peter
1092 17 James Morris
1167 17 James Morris
1093 17 Artur Svistunov
1168 17 Artur Svistunov
1094 15 Bart Skowron
1169 15 Bart Skowron
1095 14 Alex Hall
1170 14 Alex Hall
1096 13 rushabh-v
1171 13 rushabh-v
1097 13 Terry Davis
1172 13 Terry Davis
1098 13 Benjamin Ragan-Kelley
1173 13 Benjamin Ragan-Kelley
1099 8 martinRenou
1174 8 martinRenou
1100 8 farisachugthai
1175 8 farisachugthai
1101 7 dswij
1176 7 dswij
1102 7 Gal B
1177 7 Gal B
1103 7 Corentin Cadiou
1178 7 Corentin Cadiou
1104 6 yuji96
1179 6 yuji96
1105 6 Martin Skarzynski
1180 6 Martin Skarzynski
1106 6 Justin Palmer
1181 6 Justin Palmer
1107 6 Daniel Goldfarb
1182 6 Daniel Goldfarb
1108 6 Ben Greiner
1183 6 Ben Greiner
1109 5 Sammy Al Hashemi
1184 5 Sammy Al Hashemi
1110 5 Paul Ivanov
1185 5 Paul Ivanov
1111 5 Inception95
1186 5 Inception95
1112 5 Eyenpi
1187 5 Eyenpi
1113 5 Douglas Blank
1188 5 Douglas Blank
1114 5 Coco Mishra
1189 5 Coco Mishra
1115 5 Bibo Hao
1190 5 Bibo Hao
1116 5 AndrΓ© A. Gomes
1191 5 AndrΓ© A. Gomes
1117 5 Ahmed Fasih
1192 5 Ahmed Fasih
1118 4 takuya fujiwara
1193 4 takuya fujiwara
1119 4 palewire
1194 4 palewire
1120 4 Thomas A Caswell
1195 4 Thomas A Caswell
1121 4 Talley Lambert
1196 4 Talley Lambert
1122 4 Scott Sanderson
1197 4 Scott Sanderson
1123 4 Ram Rachum
1198 4 Ram Rachum
1124 4 Nick Muoh
1199 4 Nick Muoh
1125 4 Nathan Goldbaum
1200 4 Nathan Goldbaum
1126 4 Mithil Poojary
1201 4 Mithil Poojary
1127 4 Michael T
1202 4 Michael T
1128 4 Jakub Klus
1203 4 Jakub Klus
1129 4 Ian Castleden
1204 4 Ian Castleden
1130 4 Eli Rykoff
1205 4 Eli Rykoff
1131 4 Ashwin Vishnu
1206 4 Ashwin Vishnu
1132 3 谭九鼎
1207 3 谭九鼎
1133 3 sleeping
1208 3 sleeping
1134 3 Sylvain Corlay
1209 3 Sylvain Corlay
1135 3 Peter Corke
1210 3 Peter Corke
1136 3 Paul Bissex
1211 3 Paul Bissex
1137 3 Matthew Feickert
1212 3 Matthew Feickert
1138 3 Fernando Perez
1213 3 Fernando Perez
1139 3 Eric Wieser
1214 3 Eric Wieser
1140 3 Daniel Mietchen
1215 3 Daniel Mietchen
1141 3 Aditya Sathe
1216 3 Aditya Sathe
1142 3 007vedant
1217 3 007vedant
1143 2 rchiodo
1218 2 rchiodo
1144 2 nicolaslazo
1219 2 nicolaslazo
1145 2 luttik
1220 2 luttik
1146 2 gorogoroumaru
1221 2 gorogoroumaru
1147 2 foobarbyte
1222 2 foobarbyte
1148 2 bar-hen
1223 2 bar-hen
1149 2 Theo Ouzhinski
1224 2 Theo Ouzhinski
1150 2 Strawkage
1225 2 Strawkage
1151 2 Samreen Zarroug
1226 2 Samreen Zarroug
1152 2 Pete Blois
1227 2 Pete Blois
1153 2 Meysam Azad
1228 2 Meysam Azad
1154 2 Matthieu Ancellin
1229 2 Matthieu Ancellin
1155 2 Mark Schmitz
1230 2 Mark Schmitz
1156 2 Maor Kleinberger
1231 2 Maor Kleinberger
1157 2 MRCWirtz
1232 2 MRCWirtz
1158 2 Lumir Balhar
1233 2 Lumir Balhar
1159 2 Julien Rabinow
1234 2 Julien Rabinow
1160 2 Juan Luis Cano RodrΓ­guez
1235 2 Juan Luis Cano RodrΓ­guez
1161 2 Joyce Er
1236 2 Joyce Er
1162 2 Jakub
1237 2 Jakub
1163 2 Faris A Chugthai
1238 2 Faris A Chugthai
1164 2 Ethan Madden
1239 2 Ethan Madden
1165 2 Dimitri Papadopoulos
1240 2 Dimitri Papadopoulos
1166 2 Diego Fernandez
1241 2 Diego Fernandez
1167 2 Daniel Shimon
1242 2 Daniel Shimon
1168 2 Coco Bennett
1243 2 Coco Bennett
1169 2 Carlos Cordoba
1244 2 Carlos Cordoba
1170 2 Boyuan Liu
1245 2 Boyuan Liu
1171 2 BaoGiang HoangVu
1246 2 BaoGiang HoangVu
1172 2 Augusto
1247 2 Augusto
1173 2 Arthur Svistunov
1248 2 Arthur Svistunov
1174 2 Arthur Moreira
1249 2 Arthur Moreira
1175 2 Ali Nabipour
1250 2 Ali Nabipour
1176 2 Adam Hackbarth
1251 2 Adam Hackbarth
1177 1 richard
1252 1 richard
1178 1 linar-jether
1253 1 linar-jether
1179 1 lbennett
1254 1 lbennett
1180 1 juacrumar
1255 1 juacrumar
1181 1 gpotter2
1256 1 gpotter2
1182 1 digitalvirtuoso
1257 1 digitalvirtuoso
1183 1 dalthviz
1258 1 dalthviz
1184 1 Yonatan Goldschmidt
1259 1 Yonatan Goldschmidt
1185 1 Tomasz KΕ‚oczko
1260 1 Tomasz KΕ‚oczko
1186 1 Tobias Bengfort
1261 1 Tobias Bengfort
1187 1 Timur Kushukov
1262 1 Timur Kushukov
1188 1 Thomas
1263 1 Thomas
1189 1 Snir Broshi
1264 1 Snir Broshi
1190 1 Shao Yang Hong
1265 1 Shao Yang Hong
1191 1 Sanjana-03
1266 1 Sanjana-03
1192 1 Romulo Filho
1267 1 Romulo Filho
1193 1 Rodolfo Carvalho
1268 1 Rodolfo Carvalho
1194 1 Richard Shadrach
1269 1 Richard Shadrach
1195 1 Reilly Tucker Siemens
1270 1 Reilly Tucker Siemens
1196 1 Rakessh Roshan
1271 1 Rakessh Roshan
1197 1 Piers Titus van der Torren
1272 1 Piers Titus van der Torren
1198 1 PhanatosZou
1273 1 PhanatosZou
1199 1 Pavel Safronov
1274 1 Pavel Safronov
1200 1 Paulo S. Costa
1275 1 Paulo S. Costa
1201 1 Paul McCarthy
1276 1 Paul McCarthy
1202 1 NotWearingPants
1277 1 NotWearingPants
1203 1 Naelson Douglas
1278 1 Naelson Douglas
1204 1 Michael Tiemann
1279 1 Michael Tiemann
1205 1 Matt Wozniski
1280 1 Matt Wozniski
1206 1 Markus Wageringel
1281 1 Markus Wageringel
1207 1 Marcus Wirtz
1282 1 Marcus Wirtz
1208 1 Marcio Mazza
1283 1 Marcio Mazza
1209 1 LumΓ­r 'Frenzy' Balhar
1284 1 LumΓ­r 'Frenzy' Balhar
1210 1 Lightyagami1
1285 1 Lightyagami1
1211 1 Leon Anavi
1286 1 Leon Anavi
1212 1 LeafyLi
1287 1 LeafyLi
1213 1 L0uisJ0shua
1288 1 L0uisJ0shua
1214 1 Kyle Cutler
1289 1 Kyle Cutler
1215 1 Krzysztof Cybulski
1290 1 Krzysztof Cybulski
1216 1 Kevin Kirsche
1291 1 Kevin Kirsche
1217 1 KIU Shueng Chuan
1292 1 KIU Shueng Chuan
1218 1 Jonathan Slenders
1293 1 Jonathan Slenders
1219 1 Jay Qi
1294 1 Jay Qi
1220 1 Jake VanderPlas
1295 1 Jake VanderPlas
1221 1 Iwan Briquemont
1296 1 Iwan Briquemont
1222 1 Hussaina Begum Nandyala
1297 1 Hussaina Begum Nandyala
1223 1 Gordon Ball
1298 1 Gordon Ball
1224 1 Gabriel Simonetto
1299 1 Gabriel Simonetto
1225 1 Frank Tobia
1300 1 Frank Tobia
1226 1 Erik
1301 1 Erik
1227 1 Elliott Sales de Andrade
1302 1 Elliott Sales de Andrade
1228 1 Daniel Hahler
1303 1 Daniel Hahler
1229 1 Dan Green-Leipciger
1304 1 Dan Green-Leipciger
1230 1 Dan Green
1305 1 Dan Green
1231 1 Damian Yurzola
1306 1 Damian Yurzola
1232 1 Coon, Ethan T
1307 1 Coon, Ethan T
1233 1 Carol Willing
1308 1 Carol Willing
1234 1 Brian Lee
1309 1 Brian Lee
1235 1 Brendan Gerrity
1310 1 Brendan Gerrity
1236 1 Blake Griffin
1311 1 Blake Griffin
1237 1 Bastian Ebeling
1312 1 Bastian Ebeling
1238 1 Bartosz Telenczuk
1313 1 Bartosz Telenczuk
1239 1 Ankitsingh6299
1314 1 Ankitsingh6299
1240 1 Andrew Port
1315 1 Andrew Port
1241 1 Andrew J. Hesford
1316 1 Andrew J. Hesford
1242 1 Albert Zhang
1317 1 Albert Zhang
1243 1 Adam Johnson
1318 1 Adam Johnson
1244
1319
1245 This does not, of course, represent non-code contributions, for which we are also grateful.
1320 This does not, of course, represent non-code contributions, for which we are also grateful.
1246
1321
1247
1322
1248 API Changes using Frappuccino
1323 API Changes using Frappuccino
1249 -----------------------------
1324 -----------------------------
1250
1325
1251 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
1326 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
1252
1327
1253
1328
1254 The following items are new in IPython 8.0 ::
1329 The following items are new in IPython 8.0 ::
1255
1330
1256 + IPython.core.async_helpers.get_asyncio_loop()
1331 + IPython.core.async_helpers.get_asyncio_loop()
1257 + IPython.core.completer.Dict
1332 + IPython.core.completer.Dict
1258 + IPython.core.completer.Pattern
1333 + IPython.core.completer.Pattern
1259 + IPython.core.completer.Sequence
1334 + IPython.core.completer.Sequence
1260 + IPython.core.completer.__skip_doctest__
1335 + IPython.core.completer.__skip_doctest__
1261 + IPython.core.debugger.Pdb.precmd(self, line)
1336 + IPython.core.debugger.Pdb.precmd(self, line)
1262 + IPython.core.debugger.__skip_doctest__
1337 + IPython.core.debugger.__skip_doctest__
1263 + IPython.core.display.__getattr__(name)
1338 + IPython.core.display.__getattr__(name)
1264 + IPython.core.display.warn
1339 + IPython.core.display.warn
1265 + IPython.core.display_functions
1340 + IPython.core.display_functions
1266 + IPython.core.display_functions.DisplayHandle
1341 + IPython.core.display_functions.DisplayHandle
1267 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
1342 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
1268 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
1343 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
1269 + IPython.core.display_functions.__all__
1344 + IPython.core.display_functions.__all__
1270 + IPython.core.display_functions.__builtins__
1345 + IPython.core.display_functions.__builtins__
1271 + IPython.core.display_functions.__cached__
1346 + IPython.core.display_functions.__cached__
1272 + IPython.core.display_functions.__doc__
1347 + IPython.core.display_functions.__doc__
1273 + IPython.core.display_functions.__file__
1348 + IPython.core.display_functions.__file__
1274 + IPython.core.display_functions.__loader__
1349 + IPython.core.display_functions.__loader__
1275 + IPython.core.display_functions.__name__
1350 + IPython.core.display_functions.__name__
1276 + IPython.core.display_functions.__package__
1351 + IPython.core.display_functions.__package__
1277 + IPython.core.display_functions.__spec__
1352 + IPython.core.display_functions.__spec__
1278 + IPython.core.display_functions.b2a_hex
1353 + IPython.core.display_functions.b2a_hex
1279 + IPython.core.display_functions.clear_output(wait=False)
1354 + IPython.core.display_functions.clear_output(wait=False)
1280 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
1355 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
1281 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
1356 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
1282 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
1357 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
1283 + IPython.core.extensions.BUILTINS_EXTS
1358 + IPython.core.extensions.BUILTINS_EXTS
1284 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
1359 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
1285 + IPython.core.interactiveshell.Callable
1360 + IPython.core.interactiveshell.Callable
1286 + IPython.core.interactiveshell.__annotations__
1361 + IPython.core.interactiveshell.__annotations__
1287 + IPython.core.ultratb.List
1362 + IPython.core.ultratb.List
1288 + IPython.core.ultratb.Tuple
1363 + IPython.core.ultratb.Tuple
1289 + IPython.lib.pretty.CallExpression
1364 + IPython.lib.pretty.CallExpression
1290 + IPython.lib.pretty.CallExpression.factory(name)
1365 + IPython.lib.pretty.CallExpression.factory(name)
1291 + IPython.lib.pretty.RawStringLiteral
1366 + IPython.lib.pretty.RawStringLiteral
1292 + IPython.lib.pretty.RawText
1367 + IPython.lib.pretty.RawText
1293 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
1368 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
1294 + IPython.terminal.embed.Set
1369 + IPython.terminal.embed.Set
1295
1370
1296 The following items have been removed (or moved to superclass)::
1371 The following items have been removed (or moved to superclass)::
1297
1372
1298 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
1373 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
1299 - IPython.core.completer.Sentinel
1374 - IPython.core.completer.Sentinel
1300 - IPython.core.completer.skip_doctest
1375 - IPython.core.completer.skip_doctest
1301 - IPython.core.debugger.Tracer
1376 - IPython.core.debugger.Tracer
1302 - IPython.core.display.DisplayHandle
1377 - IPython.core.display.DisplayHandle
1303 - IPython.core.display.DisplayHandle.display
1378 - IPython.core.display.DisplayHandle.display
1304 - IPython.core.display.DisplayHandle.update
1379 - IPython.core.display.DisplayHandle.update
1305 - IPython.core.display.b2a_hex
1380 - IPython.core.display.b2a_hex
1306 - IPython.core.display.clear_output
1381 - IPython.core.display.clear_output
1307 - IPython.core.display.display
1382 - IPython.core.display.display
1308 - IPython.core.display.publish_display_data
1383 - IPython.core.display.publish_display_data
1309 - IPython.core.display.update_display
1384 - IPython.core.display.update_display
1310 - IPython.core.excolors.Deprec
1385 - IPython.core.excolors.Deprec
1311 - IPython.core.excolors.ExceptionColors
1386 - IPython.core.excolors.ExceptionColors
1312 - IPython.core.history.warn
1387 - IPython.core.history.warn
1313 - IPython.core.hooks.late_startup_hook
1388 - IPython.core.hooks.late_startup_hook
1314 - IPython.core.hooks.pre_run_code_hook
1389 - IPython.core.hooks.pre_run_code_hook
1315 - IPython.core.hooks.shutdown_hook
1390 - IPython.core.hooks.shutdown_hook
1316 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
1391 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
1317 - IPython.core.interactiveshell.InteractiveShell.init_readline
1392 - IPython.core.interactiveshell.InteractiveShell.init_readline
1318 - IPython.core.interactiveshell.InteractiveShell.write
1393 - IPython.core.interactiveshell.InteractiveShell.write
1319 - IPython.core.interactiveshell.InteractiveShell.write_err
1394 - IPython.core.interactiveshell.InteractiveShell.write_err
1320 - IPython.core.interactiveshell.get_default_colors
1395 - IPython.core.interactiveshell.get_default_colors
1321 - IPython.core.interactiveshell.removed_co_newlocals
1396 - IPython.core.interactiveshell.removed_co_newlocals
1322 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
1397 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
1323 - IPython.core.magics.script.PIPE
1398 - IPython.core.magics.script.PIPE
1324 - IPython.core.prefilter.PrefilterManager.init_transformers
1399 - IPython.core.prefilter.PrefilterManager.init_transformers
1325 - IPython.core.release.classifiers
1400 - IPython.core.release.classifiers
1326 - IPython.core.release.description
1401 - IPython.core.release.description
1327 - IPython.core.release.keywords
1402 - IPython.core.release.keywords
1328 - IPython.core.release.long_description
1403 - IPython.core.release.long_description
1329 - IPython.core.release.name
1404 - IPython.core.release.name
1330 - IPython.core.release.platforms
1405 - IPython.core.release.platforms
1331 - IPython.core.release.url
1406 - IPython.core.release.url
1332 - IPython.core.ultratb.VerboseTB.format_records
1407 - IPython.core.ultratb.VerboseTB.format_records
1333 - IPython.core.ultratb.find_recursion
1408 - IPython.core.ultratb.find_recursion
1334 - IPython.core.ultratb.findsource
1409 - IPython.core.ultratb.findsource
1335 - IPython.core.ultratb.fix_frame_records_filenames
1410 - IPython.core.ultratb.fix_frame_records_filenames
1336 - IPython.core.ultratb.inspect_error
1411 - IPython.core.ultratb.inspect_error
1337 - IPython.core.ultratb.is_recursion_error
1412 - IPython.core.ultratb.is_recursion_error
1338 - IPython.core.ultratb.with_patch_inspect
1413 - IPython.core.ultratb.with_patch_inspect
1339 - IPython.external.__all__
1414 - IPython.external.__all__
1340 - IPython.external.__builtins__
1415 - IPython.external.__builtins__
1341 - IPython.external.__cached__
1416 - IPython.external.__cached__
1342 - IPython.external.__doc__
1417 - IPython.external.__doc__
1343 - IPython.external.__file__
1418 - IPython.external.__file__
1344 - IPython.external.__loader__
1419 - IPython.external.__loader__
1345 - IPython.external.__name__
1420 - IPython.external.__name__
1346 - IPython.external.__package__
1421 - IPython.external.__package__
1347 - IPython.external.__path__
1422 - IPython.external.__path__
1348 - IPython.external.__spec__
1423 - IPython.external.__spec__
1349 - IPython.kernel.KernelConnectionInfo
1424 - IPython.kernel.KernelConnectionInfo
1350 - IPython.kernel.__builtins__
1425 - IPython.kernel.__builtins__
1351 - IPython.kernel.__cached__
1426 - IPython.kernel.__cached__
1352 - IPython.kernel.__warningregistry__
1427 - IPython.kernel.__warningregistry__
1353 - IPython.kernel.pkg
1428 - IPython.kernel.pkg
1354 - IPython.kernel.protocol_version
1429 - IPython.kernel.protocol_version
1355 - IPython.kernel.protocol_version_info
1430 - IPython.kernel.protocol_version_info
1356 - IPython.kernel.src
1431 - IPython.kernel.src
1357 - IPython.kernel.version_info
1432 - IPython.kernel.version_info
1358 - IPython.kernel.warn
1433 - IPython.kernel.warn
1359 - IPython.lib.backgroundjobs
1434 - IPython.lib.backgroundjobs
1360 - IPython.lib.backgroundjobs.BackgroundJobBase
1435 - IPython.lib.backgroundjobs.BackgroundJobBase
1361 - IPython.lib.backgroundjobs.BackgroundJobBase.run
1436 - IPython.lib.backgroundjobs.BackgroundJobBase.run
1362 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
1437 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
1363 - IPython.lib.backgroundjobs.BackgroundJobExpr
1438 - IPython.lib.backgroundjobs.BackgroundJobExpr
1364 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
1439 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
1365 - IPython.lib.backgroundjobs.BackgroundJobFunc
1440 - IPython.lib.backgroundjobs.BackgroundJobFunc
1366 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
1441 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
1367 - IPython.lib.backgroundjobs.BackgroundJobManager
1442 - IPython.lib.backgroundjobs.BackgroundJobManager
1368 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
1443 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
1369 - IPython.lib.backgroundjobs.BackgroundJobManager.new
1444 - IPython.lib.backgroundjobs.BackgroundJobManager.new
1370 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
1445 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
1371 - IPython.lib.backgroundjobs.BackgroundJobManager.result
1446 - IPython.lib.backgroundjobs.BackgroundJobManager.result
1372 - IPython.lib.backgroundjobs.BackgroundJobManager.status
1447 - IPython.lib.backgroundjobs.BackgroundJobManager.status
1373 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
1448 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
1374 - IPython.lib.backgroundjobs.__builtins__
1449 - IPython.lib.backgroundjobs.__builtins__
1375 - IPython.lib.backgroundjobs.__cached__
1450 - IPython.lib.backgroundjobs.__cached__
1376 - IPython.lib.backgroundjobs.__doc__
1451 - IPython.lib.backgroundjobs.__doc__
1377 - IPython.lib.backgroundjobs.__file__
1452 - IPython.lib.backgroundjobs.__file__
1378 - IPython.lib.backgroundjobs.__loader__
1453 - IPython.lib.backgroundjobs.__loader__
1379 - IPython.lib.backgroundjobs.__name__
1454 - IPython.lib.backgroundjobs.__name__
1380 - IPython.lib.backgroundjobs.__package__
1455 - IPython.lib.backgroundjobs.__package__
1381 - IPython.lib.backgroundjobs.__spec__
1456 - IPython.lib.backgroundjobs.__spec__
1382 - IPython.lib.kernel.__builtins__
1457 - IPython.lib.kernel.__builtins__
1383 - IPython.lib.kernel.__cached__
1458 - IPython.lib.kernel.__cached__
1384 - IPython.lib.kernel.__doc__
1459 - IPython.lib.kernel.__doc__
1385 - IPython.lib.kernel.__file__
1460 - IPython.lib.kernel.__file__
1386 - IPython.lib.kernel.__loader__
1461 - IPython.lib.kernel.__loader__
1387 - IPython.lib.kernel.__name__
1462 - IPython.lib.kernel.__name__
1388 - IPython.lib.kernel.__package__
1463 - IPython.lib.kernel.__package__
1389 - IPython.lib.kernel.__spec__
1464 - IPython.lib.kernel.__spec__
1390 - IPython.lib.kernel.__warningregistry__
1465 - IPython.lib.kernel.__warningregistry__
1391 - IPython.paths.fs_encoding
1466 - IPython.paths.fs_encoding
1392 - IPython.terminal.debugger.DEFAULT_BUFFER
1467 - IPython.terminal.debugger.DEFAULT_BUFFER
1393 - IPython.terminal.debugger.cursor_in_leading_ws
1468 - IPython.terminal.debugger.cursor_in_leading_ws
1394 - IPython.terminal.debugger.emacs_insert_mode
1469 - IPython.terminal.debugger.emacs_insert_mode
1395 - IPython.terminal.debugger.has_selection
1470 - IPython.terminal.debugger.has_selection
1396 - IPython.terminal.debugger.vi_insert_mode
1471 - IPython.terminal.debugger.vi_insert_mode
1397 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
1472 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
1398 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
1473 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
1399 - IPython.testing.test
1474 - IPython.testing.test
1400 - IPython.utils.contexts.NoOpContext
1475 - IPython.utils.contexts.NoOpContext
1401 - IPython.utils.io.IOStream
1476 - IPython.utils.io.IOStream
1402 - IPython.utils.io.IOStream.close
1477 - IPython.utils.io.IOStream.close
1403 - IPython.utils.io.IOStream.write
1478 - IPython.utils.io.IOStream.write
1404 - IPython.utils.io.IOStream.writelines
1479 - IPython.utils.io.IOStream.writelines
1405 - IPython.utils.io.__warningregistry__
1480 - IPython.utils.io.__warningregistry__
1406 - IPython.utils.io.atomic_writing
1481 - IPython.utils.io.atomic_writing
1407 - IPython.utils.io.stderr
1482 - IPython.utils.io.stderr
1408 - IPython.utils.io.stdin
1483 - IPython.utils.io.stdin
1409 - IPython.utils.io.stdout
1484 - IPython.utils.io.stdout
1410 - IPython.utils.io.unicode_std_stream
1485 - IPython.utils.io.unicode_std_stream
1411 - IPython.utils.path.get_ipython_cache_dir
1486 - IPython.utils.path.get_ipython_cache_dir
1412 - IPython.utils.path.get_ipython_dir
1487 - IPython.utils.path.get_ipython_dir
1413 - IPython.utils.path.get_ipython_module_path
1488 - IPython.utils.path.get_ipython_module_path
1414 - IPython.utils.path.get_ipython_package_dir
1489 - IPython.utils.path.get_ipython_package_dir
1415 - IPython.utils.path.locate_profile
1490 - IPython.utils.path.locate_profile
1416 - IPython.utils.path.unquote_filename
1491 - IPython.utils.path.unquote_filename
1417 - IPython.utils.py3compat.PY2
1492 - IPython.utils.py3compat.PY2
1418 - IPython.utils.py3compat.PY3
1493 - IPython.utils.py3compat.PY3
1419 - IPython.utils.py3compat.buffer_to_bytes
1494 - IPython.utils.py3compat.buffer_to_bytes
1420 - IPython.utils.py3compat.builtin_mod_name
1495 - IPython.utils.py3compat.builtin_mod_name
1421 - IPython.utils.py3compat.cast_bytes
1496 - IPython.utils.py3compat.cast_bytes
1422 - IPython.utils.py3compat.getcwd
1497 - IPython.utils.py3compat.getcwd
1423 - IPython.utils.py3compat.isidentifier
1498 - IPython.utils.py3compat.isidentifier
1424 - IPython.utils.py3compat.u_format
1499 - IPython.utils.py3compat.u_format
1425
1500
1426 The following signatures differ between 7.x and 8.0::
1501 The following signatures differ between 7.x and 8.0::
1427
1502
1428 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
1503 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
1429 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
1504 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
1430
1505
1431 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
1506 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
1432 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
1507 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
1433
1508
1434 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
1509 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
1435 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
1510 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
1436
1511
1437 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
1512 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
1438 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
1513 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
1439
1514
1440 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
1515 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
1441 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
1516 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
1442
1517
1443 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
1518 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
1444 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
1519 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
1445
1520
1446 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
1521 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
1447 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
1522 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
1448
1523
1449 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
1524 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
1450 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
1525 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
1451
1526
1452 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
1527 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
1453 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
1528 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
1454
1529
1455 - IPython.terminal.embed.embed(**kwargs)
1530 - IPython.terminal.embed.embed(**kwargs)
1456 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
1531 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
1457
1532
1458 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
1533 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
1459 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
1534 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
1460
1535
1461 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
1536 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
1462 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
1537 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
1463
1538
1464 - IPython.utils.path.get_py_filename(name, force_win32='None')
1539 - IPython.utils.path.get_py_filename(name, force_win32='None')
1465 + IPython.utils.path.get_py_filename(name)
1540 + IPython.utils.path.get_py_filename(name)
1466
1541
1467 The following are new attributes (that might be inherited)::
1542 The following are new attributes (that might be inherited)::
1468
1543
1469 + IPython.core.completer.IPCompleter.unicode_names
1544 + IPython.core.completer.IPCompleter.unicode_names
1470 + IPython.core.debugger.InterruptiblePdb.precmd
1545 + IPython.core.debugger.InterruptiblePdb.precmd
1471 + IPython.core.debugger.Pdb.precmd
1546 + IPython.core.debugger.Pdb.precmd
1472 + IPython.core.ultratb.AutoFormattedTB.has_colors
1547 + IPython.core.ultratb.AutoFormattedTB.has_colors
1473 + IPython.core.ultratb.ColorTB.has_colors
1548 + IPython.core.ultratb.ColorTB.has_colors
1474 + IPython.core.ultratb.FormattedTB.has_colors
1549 + IPython.core.ultratb.FormattedTB.has_colors
1475 + IPython.core.ultratb.ListTB.has_colors
1550 + IPython.core.ultratb.ListTB.has_colors
1476 + IPython.core.ultratb.SyntaxTB.has_colors
1551 + IPython.core.ultratb.SyntaxTB.has_colors
1477 + IPython.core.ultratb.TBTools.has_colors
1552 + IPython.core.ultratb.TBTools.has_colors
1478 + IPython.core.ultratb.VerboseTB.has_colors
1553 + IPython.core.ultratb.VerboseTB.has_colors
1479 + IPython.terminal.debugger.TerminalPdb.do_interact
1554 + IPython.terminal.debugger.TerminalPdb.do_interact
1480 + IPython.terminal.debugger.TerminalPdb.precmd
1555 + IPython.terminal.debugger.TerminalPdb.precmd
1481
1556
1482 The following attribute/methods have been removed::
1557 The following attribute/methods have been removed::
1483
1558
1484 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
1559 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
1485 - IPython.core.ultratb.AutoFormattedTB.format_records
1560 - IPython.core.ultratb.AutoFormattedTB.format_records
1486 - IPython.core.ultratb.ColorTB.format_records
1561 - IPython.core.ultratb.ColorTB.format_records
1487 - IPython.core.ultratb.FormattedTB.format_records
1562 - IPython.core.ultratb.FormattedTB.format_records
1488 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
1563 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
1489 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
1564 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
1490 - IPython.terminal.embed.InteractiveShellEmbed.write
1565 - IPython.terminal.embed.InteractiveShellEmbed.write
1491 - IPython.terminal.embed.InteractiveShellEmbed.write_err
1566 - IPython.terminal.embed.InteractiveShellEmbed.write_err
1492 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
1567 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
1493 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
1568 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
1494 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
1569 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
1495 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
1570 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
1496 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
1571 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
1497 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
1572 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
1498 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
1573 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
1499 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
1574 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
@@ -1,115 +1,116 b''
1 [metadata]
1 [metadata]
2 name = ipython
2 name = ipython
3 version = attr: IPython.core.release.__version__
3 version = attr: IPython.core.release.__version__
4 url = https://ipython.org
4 url = https://ipython.org
5 description = IPython: Productive Interactive Computing
5 description = IPython: Productive Interactive Computing
6 long_description_content_type = text/x-rst
6 long_description_content_type = text/x-rst
7 long_description = file: long_description.rst
7 long_description = file: long_description.rst
8 license_file = LICENSE
8 license_file = LICENSE
9 project_urls =
9 project_urls =
10 Documentation = https://ipython.readthedocs.io/
10 Documentation = https://ipython.readthedocs.io/
11 Funding = https://numfocus.org/
11 Funding = https://numfocus.org/
12 Source = https://github.com/ipython/ipython
12 Source = https://github.com/ipython/ipython
13 Tracker = https://github.com/ipython/ipython/issues
13 Tracker = https://github.com/ipython/ipython/issues
14 keywords = Interactive, Interpreter, Shell, Embedding
14 keywords = Interactive, Interpreter, Shell, Embedding
15 platforms = Linux, Mac OSX, Windows
15 platforms = Linux, Mac OSX, Windows
16 classifiers =
16 classifiers =
17 Framework :: IPython
17 Framework :: IPython
18 Framework :: Jupyter
18 Framework :: Jupyter
19 Intended Audience :: Developers
19 Intended Audience :: Developers
20 Intended Audience :: Science/Research
20 Intended Audience :: Science/Research
21 License :: OSI Approved :: BSD License
21 License :: OSI Approved :: BSD License
22 Programming Language :: Python
22 Programming Language :: Python
23 Programming Language :: Python :: 3
23 Programming Language :: Python :: 3
24 Programming Language :: Python :: 3 :: Only
24 Programming Language :: Python :: 3 :: Only
25 Topic :: System :: Shells
25 Topic :: System :: Shells
26
26
27 [options]
27 [options]
28 packages = find:
28 packages = find:
29 python_requires = >=3.8
29 python_requires = >=3.8
30 zip_safe = False
30 zip_safe = False
31 install_requires =
31 install_requires =
32 appnope; sys_platform == "darwin"
32 appnope; sys_platform == "darwin"
33 backcall
33 backcall
34 colorama; sys_platform == "win32"
34 colorama; sys_platform == "win32"
35 decorator
35 decorator
36 jedi>=0.16
36 jedi>=0.16
37 matplotlib-inline
37 matplotlib-inline
38 pexpect>4.3; sys_platform != "win32"
38 pexpect>4.3; sys_platform != "win32"
39 pickleshare
39 pickleshare
40 prompt_toolkit>=3.0.30,<3.1.0,!=3.0.37
40 prompt_toolkit>=3.0.30,<3.1.0,!=3.0.37
41 pygments>=2.4.0
41 pygments>=2.4.0
42 stack_data
42 stack_data
43 traitlets>=5
43 traitlets>=5
44 typing_extensions ; python_version<'3.10'
44
45
45 [options.extras_require]
46 [options.extras_require]
46 black =
47 black =
47 black
48 black
48 doc =
49 doc =
49 ipykernel
50 ipykernel
50 setuptools>=18.5
51 setuptools>=18.5
51 sphinx>=1.3
52 sphinx>=1.3
52 sphinx-rtd-theme
53 sphinx-rtd-theme
53 docrepr
54 docrepr
54 matplotlib
55 matplotlib
55 stack_data
56 stack_data
56 pytest<7
57 pytest<7
57 typing_extensions
58 typing_extensions
58 %(test)s
59 %(test)s
59 kernel =
60 kernel =
60 ipykernel
61 ipykernel
61 nbconvert =
62 nbconvert =
62 nbconvert
63 nbconvert
63 nbformat =
64 nbformat =
64 nbformat
65 nbformat
65 notebook =
66 notebook =
66 ipywidgets
67 ipywidgets
67 notebook
68 notebook
68 parallel =
69 parallel =
69 ipyparallel
70 ipyparallel
70 qtconsole =
71 qtconsole =
71 qtconsole
72 qtconsole
72 terminal =
73 terminal =
73 test =
74 test =
74 pytest<7.1
75 pytest<7.1
75 pytest-asyncio
76 pytest-asyncio
76 testpath
77 testpath
77 test_extra =
78 test_extra =
78 %(test)s
79 %(test)s
79 curio
80 curio
80 matplotlib!=3.2.0
81 matplotlib!=3.2.0
81 nbformat
82 nbformat
82 numpy>=1.21
83 numpy>=1.21
83 pandas
84 pandas
84 trio
85 trio
85 all =
86 all =
86 %(black)s
87 %(black)s
87 %(doc)s
88 %(doc)s
88 %(kernel)s
89 %(kernel)s
89 %(nbconvert)s
90 %(nbconvert)s
90 %(nbformat)s
91 %(nbformat)s
91 %(notebook)s
92 %(notebook)s
92 %(parallel)s
93 %(parallel)s
93 %(qtconsole)s
94 %(qtconsole)s
94 %(terminal)s
95 %(terminal)s
95 %(test_extra)s
96 %(test_extra)s
96 %(test)s
97 %(test)s
97
98
98 [options.packages.find]
99 [options.packages.find]
99 exclude =
100 exclude =
100 setupext
101 setupext
101
102
102 [options.package_data]
103 [options.package_data]
103 IPython = py.typed
104 IPython = py.typed
104 IPython.core = profile/README*
105 IPython.core = profile/README*
105 IPython.core.tests = *.png, *.jpg, daft_extension/*.py
106 IPython.core.tests = *.png, *.jpg, daft_extension/*.py
106 IPython.lib.tests = *.wav
107 IPython.lib.tests = *.wav
107 IPython.testing.plugin = *.txt
108 IPython.testing.plugin = *.txt
108
109
109 [velin]
110 [velin]
110 ignore_patterns =
111 ignore_patterns =
111 IPython/core/tests
112 IPython/core/tests
112 IPython/testing
113 IPython/testing
113
114
114 [tool.black]
115 [tool.black]
115 exclude = 'timing\.py'
116 exclude = 'timing\.py'
General Comments 0
You need to be logged in to leave comments. Login now