##// END OF EJS Templates
some manual fixes
Matthias Bussonnier -
Show More
@@ -1,3660 +1,3658
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 builtins as builtin_mod
17 import builtins as builtin_mod
18 import functools
18 import functools
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pathlib import Path
31 from pathlib import Path
32 from pickleshare import PickleShareDB
32 from pickleshare import PickleShareDB
33
33
34 from traitlets.config.configurable import SingletonConfigurable
34 from traitlets.config.configurable import SingletonConfigurable
35 from traitlets.utils.importstring import import_item
35 from traitlets.utils.importstring import import_item
36 from IPython.core import oinspect
36 from IPython.core import oinspect
37 from IPython.core import magic
37 from IPython.core import magic
38 from IPython.core import page
38 from IPython.core import page
39 from IPython.core import prefilter
39 from IPython.core import prefilter
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.alias import Alias, AliasManager
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.events import EventManager, available_events
44 from IPython.core.events import EventManager, available_events
45 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
46 from IPython.core.debugger import InterruptiblePdb
46 from IPython.core.debugger import InterruptiblePdb
47 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.display_trap import DisplayTrap
48 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displayhook import DisplayHook
49 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.displaypub import DisplayPublisher
50 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.error import InputRejected, UsageError
51 from IPython.core.extensions import ExtensionManager
51 from IPython.core.extensions import ExtensionManager
52 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.formatters import DisplayFormatter
53 from IPython.core.history import HistoryManager
53 from IPython.core.history import HistoryManager
54 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
55 from IPython.core.logger import Logger
55 from IPython.core.logger import Logger
56 from IPython.core.macro import Macro
56 from IPython.core.macro import Macro
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.prefilter import PrefilterManager
59 from IPython.core.profiledir import ProfileDir
59 from IPython.core.profiledir import ProfileDir
60 from IPython.core.usage import default_banner
60 from IPython.core.usage import default_banner
61 from IPython.display import display
61 from IPython.display import display
62 from IPython.testing.skipdoctest import skip_doctest
62 from IPython.testing.skipdoctest import skip_doctest
63 from IPython.utils import PyColorize
63 from IPython.utils import PyColorize
64 from IPython.utils import io
64 from IPython.utils import io
65 from IPython.utils import py3compat
65 from IPython.utils import py3compat
66 from IPython.utils import openpy
66 from IPython.utils import openpy
67 from IPython.utils.decorators import undoc
67 from IPython.utils.decorators import undoc
68 from IPython.utils.io import ask_yes_no
68 from IPython.utils.io import ask_yes_no
69 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
70 from IPython.paths import get_ipython_dir
70 from IPython.paths import get_ipython_dir
71 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
72 from IPython.utils.process import system, getoutput
72 from IPython.utils.process import system, getoutput
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.tempdir import TemporaryDirectory
76 from IPython.utils.tempdir import TemporaryDirectory
77 from traitlets import (
77 from traitlets import (
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 observe, default, validate, Any
79 observe, default, validate, Any
80 )
80 )
81 from warnings import warn
81 from warnings import warn
82 from logging import error
82 from logging import error
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 from typing import List as ListType, Tuple, Optional, Callable
85 from typing import List as ListType, Tuple, Optional, Callable
86 from ast import stmt
86 from ast import stmt
87
87
88 sphinxify: Optional[Callable]
88 sphinxify: Optional[Callable]
89
89
90 try:
90 try:
91 import docrepr.sphinxify as sphx
91 import docrepr.sphinxify as sphx
92
92
93 def sphinxify(doc):
93 def sphinxify(doc):
94 with TemporaryDirectory() as dirname:
94 with TemporaryDirectory() as dirname:
95 return {
95 return {
96 'text/html': sphx.sphinxify(doc, dirname),
96 'text/html': sphx.sphinxify(doc, dirname),
97 'text/plain': doc
97 'text/plain': doc
98 }
98 }
99 except ImportError:
99 except ImportError:
100 sphinxify = None
100 sphinxify = None
101
101
102
102
103 class ProvisionalWarning(DeprecationWarning):
103 class ProvisionalWarning(DeprecationWarning):
104 """
104 """
105 Warning class for unstable features
105 Warning class for unstable features
106 """
106 """
107 pass
107 pass
108
108
109 from ast import Module
109 from ast import Module
110
110
111 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
111 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
112 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
112 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
113
113
114 #-----------------------------------------------------------------------------
114 #-----------------------------------------------------------------------------
115 # Await Helpers
115 # Await Helpers
116 #-----------------------------------------------------------------------------
116 #-----------------------------------------------------------------------------
117
117
118 # we still need to run things using the asyncio eventloop, but there is no
118 # we still need to run things using the asyncio eventloop, but there is no
119 # async integration
119 # async integration
120 from .async_helpers import _asyncio_runner, _pseudo_sync_runner
120 from .async_helpers import _asyncio_runner, _pseudo_sync_runner
121 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
121 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
122
122
123 #-----------------------------------------------------------------------------
123 #-----------------------------------------------------------------------------
124 # Globals
124 # Globals
125 #-----------------------------------------------------------------------------
125 #-----------------------------------------------------------------------------
126
126
127 # compiled regexps for autoindent management
127 # compiled regexps for autoindent management
128 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
128 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
129
129
130 #-----------------------------------------------------------------------------
130 #-----------------------------------------------------------------------------
131 # Utilities
131 # Utilities
132 #-----------------------------------------------------------------------------
132 #-----------------------------------------------------------------------------
133
133
134 @undoc
134 @undoc
135 def softspace(file, newvalue):
135 def softspace(file, newvalue):
136 """Copied from code.py, to remove the dependency"""
136 """Copied from code.py, to remove the dependency"""
137
137
138 oldvalue = 0
138 oldvalue = 0
139 try:
139 try:
140 oldvalue = file.softspace
140 oldvalue = file.softspace
141 except AttributeError:
141 except AttributeError:
142 pass
142 pass
143 try:
143 try:
144 file.softspace = newvalue
144 file.softspace = newvalue
145 except (AttributeError, TypeError):
145 except (AttributeError, TypeError):
146 # "attribute-less object" or "read-only attributes"
146 # "attribute-less object" or "read-only attributes"
147 pass
147 pass
148 return oldvalue
148 return oldvalue
149
149
150 @undoc
150 @undoc
151 def no_op(*a, **kw):
151 def no_op(*a, **kw):
152 pass
152 pass
153
153
154
154
155 class SpaceInInput(Exception): pass
155 class SpaceInInput(Exception): pass
156
156
157
157
158 class SeparateUnicode(Unicode):
158 class SeparateUnicode(Unicode):
159 r"""A Unicode subclass to validate separate_in, separate_out, etc.
159 r"""A Unicode subclass to validate separate_in, separate_out, etc.
160
160
161 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
161 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
162 """
162 """
163
163
164 def validate(self, obj, value):
164 def validate(self, obj, value):
165 if value == '0': value = ''
165 if value == '0': value = ''
166 value = value.replace('\\n','\n')
166 value = value.replace('\\n','\n')
167 return super(SeparateUnicode, self).validate(obj, value)
167 return super(SeparateUnicode, self).validate(obj, value)
168
168
169
169
170 @undoc
170 @undoc
171 class DummyMod(object):
171 class DummyMod(object):
172 """A dummy module used for IPython's interactive module when
172 """A dummy module used for IPython's interactive module when
173 a namespace must be assigned to the module's __dict__."""
173 a namespace must be assigned to the module's __dict__."""
174 __spec__ = None
174 __spec__ = None
175
175
176
176
177 class ExecutionInfo(object):
177 class ExecutionInfo(object):
178 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
178 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
179
179
180 Stores information about what is going to happen.
180 Stores information about what is going to happen.
181 """
181 """
182 raw_cell = None
182 raw_cell = None
183 store_history = False
183 store_history = False
184 silent = False
184 silent = False
185 shell_futures = True
185 shell_futures = True
186
186
187 def __init__(self, raw_cell, store_history, silent, shell_futures):
187 def __init__(self, raw_cell, store_history, silent, shell_futures):
188 self.raw_cell = raw_cell
188 self.raw_cell = raw_cell
189 self.store_history = store_history
189 self.store_history = store_history
190 self.silent = silent
190 self.silent = silent
191 self.shell_futures = shell_futures
191 self.shell_futures = shell_futures
192
192
193 def __repr__(self):
193 def __repr__(self):
194 name = self.__class__.__qualname__
194 name = self.__class__.__qualname__
195 raw_cell = ((self.raw_cell[:50] + '..')
195 raw_cell = ((self.raw_cell[:50] + '..')
196 if len(self.raw_cell) > 50 else self.raw_cell)
196 if len(self.raw_cell) > 50 else self.raw_cell)
197 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
197 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
198 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
198 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
199
199
200
200
201 class ExecutionResult(object):
201 class ExecutionResult(object):
202 """The result of a call to :meth:`InteractiveShell.run_cell`
202 """The result of a call to :meth:`InteractiveShell.run_cell`
203
203
204 Stores information about what took place.
204 Stores information about what took place.
205 """
205 """
206 execution_count = None
206 execution_count = None
207 error_before_exec = None
207 error_before_exec = None
208 error_in_exec: Optional[BaseException] = None
208 error_in_exec: Optional[BaseException] = None
209 info = None
209 info = None
210 result = None
210 result = None
211
211
212 def __init__(self, info):
212 def __init__(self, info):
213 self.info = info
213 self.info = info
214
214
215 @property
215 @property
216 def success(self):
216 def success(self):
217 return (self.error_before_exec is None) and (self.error_in_exec is None)
217 return (self.error_before_exec is None) and (self.error_in_exec is None)
218
218
219 def raise_error(self):
219 def raise_error(self):
220 """Reraises error if `success` is `False`, otherwise does nothing"""
220 """Reraises error if `success` is `False`, otherwise does nothing"""
221 if self.error_before_exec is not None:
221 if self.error_before_exec is not None:
222 raise self.error_before_exec
222 raise self.error_before_exec
223 if self.error_in_exec is not None:
223 if self.error_in_exec is not None:
224 raise self.error_in_exec
224 raise self.error_in_exec
225
225
226 def __repr__(self):
226 def __repr__(self):
227 name = self.__class__.__qualname__
227 name = self.__class__.__qualname__
228 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
228 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
229 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
229 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
230
230
231
231
232 class InteractiveShell(SingletonConfigurable):
232 class InteractiveShell(SingletonConfigurable):
233 """An enhanced, interactive shell for Python."""
233 """An enhanced, interactive shell for Python."""
234
234
235 _instance = None
235 _instance = None
236
236
237 ast_transformers = List([], help=
237 ast_transformers = List([], help=
238 """
238 """
239 A list of ast.NodeTransformer subclass instances, which will be applied
239 A list of ast.NodeTransformer subclass instances, which will be applied
240 to user input before code is run.
240 to user input before code is run.
241 """
241 """
242 ).tag(config=True)
242 ).tag(config=True)
243
243
244 autocall = Enum((0,1,2), default_value=0, help=
244 autocall = Enum((0,1,2), default_value=0, help=
245 """
245 """
246 Make IPython automatically call any callable object even if you didn't
246 Make IPython automatically call any callable object even if you didn't
247 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
247 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
248 automatically. The value can be '0' to disable the feature, '1' for
248 automatically. The value can be '0' to disable the feature, '1' for
249 'smart' autocall, where it is not applied if there are no more
249 'smart' autocall, where it is not applied if there are no more
250 arguments on the line, and '2' for 'full' autocall, where all callable
250 arguments on the line, and '2' for 'full' autocall, where all callable
251 objects are automatically called (even if no arguments are present).
251 objects are automatically called (even if no arguments are present).
252 """
252 """
253 ).tag(config=True)
253 ).tag(config=True)
254
254
255 autoindent = Bool(True, help=
255 autoindent = Bool(True, help=
256 """
256 """
257 Autoindent IPython code entered interactively.
257 Autoindent IPython code entered interactively.
258 """
258 """
259 ).tag(config=True)
259 ).tag(config=True)
260
260
261 autoawait = Bool(True, help=
261 autoawait = Bool(True, help=
262 """
262 """
263 Automatically run await statement in the top level repl.
263 Automatically run await statement in the top level repl.
264 """
264 """
265 ).tag(config=True)
265 ).tag(config=True)
266
266
267 loop_runner_map ={
267 loop_runner_map ={
268 'asyncio':(_asyncio_runner, True),
268 'asyncio':(_asyncio_runner, True),
269 'curio':(_curio_runner, True),
269 'curio':(_curio_runner, True),
270 'trio':(_trio_runner, True),
270 'trio':(_trio_runner, True),
271 'sync': (_pseudo_sync_runner, False)
271 'sync': (_pseudo_sync_runner, False)
272 }
272 }
273
273
274 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
274 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
275 allow_none=True,
275 allow_none=True,
276 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
276 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
277 ).tag(config=True)
277 ).tag(config=True)
278
278
279 @default('loop_runner')
279 @default('loop_runner')
280 def _default_loop_runner(self):
280 def _default_loop_runner(self):
281 return import_item("IPython.core.interactiveshell._asyncio_runner")
281 return import_item("IPython.core.interactiveshell._asyncio_runner")
282
282
283 @validate('loop_runner')
283 @validate('loop_runner')
284 def _import_runner(self, proposal):
284 def _import_runner(self, proposal):
285 if isinstance(proposal.value, str):
285 if isinstance(proposal.value, str):
286 if proposal.value in self.loop_runner_map:
286 if proposal.value in self.loop_runner_map:
287 runner, autoawait = self.loop_runner_map[proposal.value]
287 runner, autoawait = self.loop_runner_map[proposal.value]
288 self.autoawait = autoawait
288 self.autoawait = autoawait
289 return runner
289 return runner
290 runner = import_item(proposal.value)
290 runner = import_item(proposal.value)
291 if not callable(runner):
291 if not callable(runner):
292 raise ValueError('loop_runner must be callable')
292 raise ValueError('loop_runner must be callable')
293 return runner
293 return runner
294 if not callable(proposal.value):
294 if not callable(proposal.value):
295 raise ValueError('loop_runner must be callable')
295 raise ValueError('loop_runner must be callable')
296 return proposal.value
296 return proposal.value
297
297
298 automagic = Bool(True, help=
298 automagic = Bool(True, help=
299 """
299 """
300 Enable magic commands to be called without the leading %.
300 Enable magic commands to be called without the leading %.
301 """
301 """
302 ).tag(config=True)
302 ).tag(config=True)
303
303
304 banner1 = Unicode(default_banner,
304 banner1 = Unicode(default_banner,
305 help="""The part of the banner to be printed before the profile"""
305 help="""The part of the banner to be printed before the profile"""
306 ).tag(config=True)
306 ).tag(config=True)
307 banner2 = Unicode('',
307 banner2 = Unicode('',
308 help="""The part of the banner to be printed after the profile"""
308 help="""The part of the banner to be printed after the profile"""
309 ).tag(config=True)
309 ).tag(config=True)
310
310
311 cache_size = Integer(1000, help=
311 cache_size = Integer(1000, help=
312 """
312 """
313 Set the size of the output cache. The default is 1000, you can
313 Set the size of the output cache. The default is 1000, you can
314 change it permanently in your config file. Setting it to 0 completely
314 change it permanently in your config file. Setting it to 0 completely
315 disables the caching system, and the minimum value accepted is 3 (if
315 disables the caching system, and the minimum value accepted is 3 (if
316 you provide a value less than 3, it is reset to 0 and a warning is
316 you provide a value less than 3, it is reset to 0 and a warning is
317 issued). This limit is defined because otherwise you'll spend more
317 issued). This limit is defined because otherwise you'll spend more
318 time re-flushing a too small cache than working
318 time re-flushing a too small cache than working
319 """
319 """
320 ).tag(config=True)
320 ).tag(config=True)
321 color_info = Bool(True, help=
321 color_info = Bool(True, help=
322 """
322 """
323 Use colors for displaying information about objects. Because this
323 Use colors for displaying information about objects. Because this
324 information is passed through a pager (like 'less'), and some pagers
324 information is passed through a pager (like 'less'), and some pagers
325 get confused with color codes, this capability can be turned off.
325 get confused with color codes, this capability can be turned off.
326 """
326 """
327 ).tag(config=True)
327 ).tag(config=True)
328 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
328 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
329 default_value='Neutral',
329 default_value='Neutral',
330 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
330 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
331 ).tag(config=True)
331 ).tag(config=True)
332 debug = Bool(False).tag(config=True)
332 debug = Bool(False).tag(config=True)
333 disable_failing_post_execute = Bool(False,
333 disable_failing_post_execute = Bool(False,
334 help="Don't call post-execute functions that have failed in the past."
334 help="Don't call post-execute functions that have failed in the past."
335 ).tag(config=True)
335 ).tag(config=True)
336 display_formatter = Instance(DisplayFormatter, allow_none=True)
336 display_formatter = Instance(DisplayFormatter, allow_none=True)
337 displayhook_class = Type(DisplayHook)
337 displayhook_class = Type(DisplayHook)
338 display_pub_class = Type(DisplayPublisher)
338 display_pub_class = Type(DisplayPublisher)
339 compiler_class = Type(CachingCompiler)
339 compiler_class = Type(CachingCompiler)
340
340
341 sphinxify_docstring = Bool(False, help=
341 sphinxify_docstring = Bool(False, help=
342 """
342 """
343 Enables rich html representation of docstrings. (This requires the
343 Enables rich html representation of docstrings. (This requires the
344 docrepr module).
344 docrepr module).
345 """).tag(config=True)
345 """).tag(config=True)
346
346
347 @observe("sphinxify_docstring")
347 @observe("sphinxify_docstring")
348 def _sphinxify_docstring_changed(self, change):
348 def _sphinxify_docstring_changed(self, change):
349 if change['new']:
349 if change['new']:
350 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
350 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
351
351
352 enable_html_pager = Bool(False, help=
352 enable_html_pager = Bool(False, help=
353 """
353 """
354 (Provisional API) enables html representation in mime bundles sent
354 (Provisional API) enables html representation in mime bundles sent
355 to pagers.
355 to pagers.
356 """).tag(config=True)
356 """).tag(config=True)
357
357
358 @observe("enable_html_pager")
358 @observe("enable_html_pager")
359 def _enable_html_pager_changed(self, change):
359 def _enable_html_pager_changed(self, change):
360 if change['new']:
360 if change['new']:
361 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
361 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
362
362
363 data_pub_class = None
363 data_pub_class = None
364
364
365 exit_now = Bool(False)
365 exit_now = Bool(False)
366 exiter = Instance(ExitAutocall)
366 exiter = Instance(ExitAutocall)
367 @default('exiter')
367 @default('exiter')
368 def _exiter_default(self):
368 def _exiter_default(self):
369 return ExitAutocall(self)
369 return ExitAutocall(self)
370 # Monotonically increasing execution counter
370 # Monotonically increasing execution counter
371 execution_count = Integer(1)
371 execution_count = Integer(1)
372 filename = Unicode("<ipython console>")
372 filename = Unicode("<ipython console>")
373 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
373 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
374
374
375 # Used to transform cells before running them, and check whether code is complete
375 # Used to transform cells before running them, and check whether code is complete
376 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
376 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
377 ())
377 ())
378
378
379 @property
379 @property
380 def input_transformers_cleanup(self):
380 def input_transformers_cleanup(self):
381 return self.input_transformer_manager.cleanup_transforms
381 return self.input_transformer_manager.cleanup_transforms
382
382
383 input_transformers_post = List([],
383 input_transformers_post = List([],
384 help="A list of string input transformers, to be applied after IPython's "
384 help="A list of string input transformers, to be applied after IPython's "
385 "own input transformations."
385 "own input transformations."
386 )
386 )
387
387
388 @property
388 @property
389 def input_splitter(self):
389 def input_splitter(self):
390 """Make this available for backward compatibility (pre-7.0 release) with existing code.
390 """Make this available for backward compatibility (pre-7.0 release) with existing code.
391
391
392 For example, ipykernel ipykernel currently uses
392 For example, ipykernel ipykernel currently uses
393 `shell.input_splitter.check_complete`
393 `shell.input_splitter.check_complete`
394 """
394 """
395 from warnings import warn
395 from warnings import warn
396 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
396 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
397 DeprecationWarning, stacklevel=2
397 DeprecationWarning, stacklevel=2
398 )
398 )
399 return self.input_transformer_manager
399 return self.input_transformer_manager
400
400
401 logstart = Bool(False, help=
401 logstart = Bool(False, help=
402 """
402 """
403 Start logging to the default log file in overwrite mode.
403 Start logging to the default log file in overwrite mode.
404 Use `logappend` to specify a log file to **append** logs to.
404 Use `logappend` to specify a log file to **append** logs to.
405 """
405 """
406 ).tag(config=True)
406 ).tag(config=True)
407 logfile = Unicode('', help=
407 logfile = Unicode('', help=
408 """
408 """
409 The name of the logfile to use.
409 The name of the logfile to use.
410 """
410 """
411 ).tag(config=True)
411 ).tag(config=True)
412 logappend = Unicode('', help=
412 logappend = Unicode('', help=
413 """
413 """
414 Start logging to the given file in append mode.
414 Start logging to the given file in append mode.
415 Use `logfile` to specify a log file to **overwrite** logs to.
415 Use `logfile` to specify a log file to **overwrite** logs to.
416 """
416 """
417 ).tag(config=True)
417 ).tag(config=True)
418 object_info_string_level = Enum((0,1,2), default_value=0,
418 object_info_string_level = Enum((0,1,2), default_value=0,
419 ).tag(config=True)
419 ).tag(config=True)
420 pdb = Bool(False, help=
420 pdb = Bool(False, help=
421 """
421 """
422 Automatically call the pdb debugger after every exception.
422 Automatically call the pdb debugger after every exception.
423 """
423 """
424 ).tag(config=True)
424 ).tag(config=True)
425 display_page = Bool(False,
425 display_page = Bool(False,
426 help="""If True, anything that would be passed to the pager
426 help="""If True, anything that would be passed to the pager
427 will be displayed as regular output instead."""
427 will be displayed as regular output instead."""
428 ).tag(config=True)
428 ).tag(config=True)
429
429
430
430
431 show_rewritten_input = Bool(True,
431 show_rewritten_input = Bool(True,
432 help="Show rewritten input, e.g. for autocall."
432 help="Show rewritten input, e.g. for autocall."
433 ).tag(config=True)
433 ).tag(config=True)
434
434
435 quiet = Bool(False).tag(config=True)
435 quiet = Bool(False).tag(config=True)
436
436
437 history_length = Integer(10000,
437 history_length = Integer(10000,
438 help='Total length of command history'
438 help='Total length of command history'
439 ).tag(config=True)
439 ).tag(config=True)
440
440
441 history_load_length = Integer(1000, help=
441 history_load_length = Integer(1000, help=
442 """
442 """
443 The number of saved history entries to be loaded
443 The number of saved history entries to be loaded
444 into the history buffer at startup.
444 into the history buffer at startup.
445 """
445 """
446 ).tag(config=True)
446 ).tag(config=True)
447
447
448 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
448 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
449 default_value='last_expr',
449 default_value='last_expr',
450 help="""
450 help="""
451 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
451 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
452 which nodes should be run interactively (displaying output from expressions).
452 which nodes should be run interactively (displaying output from expressions).
453 """
453 """
454 ).tag(config=True)
454 ).tag(config=True)
455
455
456 # TODO: this part of prompt management should be moved to the frontends.
456 # TODO: this part of prompt management should be moved to the frontends.
457 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
457 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
458 separate_in = SeparateUnicode('\n').tag(config=True)
458 separate_in = SeparateUnicode('\n').tag(config=True)
459 separate_out = SeparateUnicode('').tag(config=True)
459 separate_out = SeparateUnicode('').tag(config=True)
460 separate_out2 = SeparateUnicode('').tag(config=True)
460 separate_out2 = SeparateUnicode('').tag(config=True)
461 wildcards_case_sensitive = Bool(True).tag(config=True)
461 wildcards_case_sensitive = Bool(True).tag(config=True)
462 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
462 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
463 default_value='Context',
463 default_value='Context',
464 help="Switch modes for the IPython exception handlers."
464 help="Switch modes for the IPython exception handlers."
465 ).tag(config=True)
465 ).tag(config=True)
466
466
467 # Subcomponents of InteractiveShell
467 # Subcomponents of InteractiveShell
468 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
468 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
469 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
469 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
470 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
470 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
471 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
471 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
472 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
472 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
473 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
473 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
474 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
474 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
475 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
475 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
476
476
477 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
477 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
478 @property
478 @property
479 def profile(self):
479 def profile(self):
480 if self.profile_dir is not None:
480 if self.profile_dir is not None:
481 name = os.path.basename(self.profile_dir.location)
481 name = os.path.basename(self.profile_dir.location)
482 return name.replace('profile_','')
482 return name.replace('profile_','')
483
483
484
484
485 # Private interface
485 # Private interface
486 _post_execute = Dict()
486 _post_execute = Dict()
487
487
488 # Tracks any GUI loop loaded for pylab
488 # Tracks any GUI loop loaded for pylab
489 pylab_gui_select = None
489 pylab_gui_select = None
490
490
491 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
491 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
492
492
493 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
493 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
494
494
495 def __init__(self, ipython_dir=None, profile_dir=None,
495 def __init__(self, ipython_dir=None, profile_dir=None,
496 user_module=None, user_ns=None,
496 user_module=None, user_ns=None,
497 custom_exceptions=((), None), **kwargs):
497 custom_exceptions=((), None), **kwargs):
498
498
499 # This is where traits with a config_key argument are updated
499 # This is where traits with a config_key argument are updated
500 # from the values on config.
500 # from the values on config.
501 super(InteractiveShell, self).__init__(**kwargs)
501 super(InteractiveShell, self).__init__(**kwargs)
502 if 'PromptManager' in self.config:
502 if 'PromptManager' in self.config:
503 warn('As of IPython 5.0 `PromptManager` config will have no effect'
503 warn('As of IPython 5.0 `PromptManager` config will have no effect'
504 ' and has been replaced by TerminalInteractiveShell.prompts_class')
504 ' and has been replaced by TerminalInteractiveShell.prompts_class')
505 self.configurables = [self]
505 self.configurables = [self]
506
506
507 # These are relatively independent and stateless
507 # These are relatively independent and stateless
508 self.init_ipython_dir(ipython_dir)
508 self.init_ipython_dir(ipython_dir)
509 self.init_profile_dir(profile_dir)
509 self.init_profile_dir(profile_dir)
510 self.init_instance_attrs()
510 self.init_instance_attrs()
511 self.init_environment()
511 self.init_environment()
512
512
513 # Check if we're in a virtualenv, and set up sys.path.
513 # Check if we're in a virtualenv, and set up sys.path.
514 self.init_virtualenv()
514 self.init_virtualenv()
515
515
516 # Create namespaces (user_ns, user_global_ns, etc.)
516 # Create namespaces (user_ns, user_global_ns, etc.)
517 self.init_create_namespaces(user_module, user_ns)
517 self.init_create_namespaces(user_module, user_ns)
518 # This has to be done after init_create_namespaces because it uses
518 # This has to be done after init_create_namespaces because it uses
519 # something in self.user_ns, but before init_sys_modules, which
519 # something in self.user_ns, but before init_sys_modules, which
520 # is the first thing to modify sys.
520 # is the first thing to modify sys.
521 # TODO: When we override sys.stdout and sys.stderr before this class
521 # TODO: When we override sys.stdout and sys.stderr before this class
522 # is created, we are saving the overridden ones here. Not sure if this
522 # is created, we are saving the overridden ones here. Not sure if this
523 # is what we want to do.
523 # is what we want to do.
524 self.save_sys_module_state()
524 self.save_sys_module_state()
525 self.init_sys_modules()
525 self.init_sys_modules()
526
526
527 # While we're trying to have each part of the code directly access what
527 # While we're trying to have each part of the code directly access what
528 # it needs without keeping redundant references to objects, we have too
528 # it needs without keeping redundant references to objects, we have too
529 # much legacy code that expects ip.db to exist.
529 # much legacy code that expects ip.db to exist.
530 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
530 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
531
531
532 self.init_history()
532 self.init_history()
533 self.init_encoding()
533 self.init_encoding()
534 self.init_prefilter()
534 self.init_prefilter()
535
535
536 self.init_syntax_highlighting()
536 self.init_syntax_highlighting()
537 self.init_hooks()
537 self.init_hooks()
538 self.init_events()
538 self.init_events()
539 self.init_pushd_popd_magic()
539 self.init_pushd_popd_magic()
540 self.init_user_ns()
540 self.init_user_ns()
541 self.init_logger()
541 self.init_logger()
542 self.init_builtins()
542 self.init_builtins()
543
543
544 # The following was in post_config_initialization
544 # The following was in post_config_initialization
545 self.init_inspector()
545 self.init_inspector()
546 self.raw_input_original = input
546 self.raw_input_original = input
547 self.init_completer()
547 self.init_completer()
548 # TODO: init_io() needs to happen before init_traceback handlers
548 # TODO: init_io() needs to happen before init_traceback handlers
549 # because the traceback handlers hardcode the stdout/stderr streams.
549 # because the traceback handlers hardcode the stdout/stderr streams.
550 # This logic in in debugger.Pdb and should eventually be changed.
550 # This logic in in debugger.Pdb and should eventually be changed.
551 self.init_io()
551 self.init_io()
552 self.init_traceback_handlers(custom_exceptions)
552 self.init_traceback_handlers(custom_exceptions)
553 self.init_prompts()
553 self.init_prompts()
554 self.init_display_formatter()
554 self.init_display_formatter()
555 self.init_display_pub()
555 self.init_display_pub()
556 self.init_data_pub()
556 self.init_data_pub()
557 self.init_displayhook()
557 self.init_displayhook()
558 self.init_magics()
558 self.init_magics()
559 self.init_alias()
559 self.init_alias()
560 self.init_logstart()
560 self.init_logstart()
561 self.init_pdb()
561 self.init_pdb()
562 self.init_extension_manager()
562 self.init_extension_manager()
563 self.init_payload()
563 self.init_payload()
564 self.hooks.late_startup_hook()
564 self.hooks.late_startup_hook()
565 self.events.trigger('shell_initialized', self)
565 self.events.trigger('shell_initialized', self)
566 atexit.register(self.atexit_operations)
566 atexit.register(self.atexit_operations)
567
567
568 # The trio runner is used for running Trio in the foreground thread. It
568 # The trio runner is used for running Trio in the foreground thread. It
569 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
569 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
570 # which calls `trio.run()` for every cell. This runner runs all cells
570 # which calls `trio.run()` for every cell. This runner runs all cells
571 # inside a single Trio event loop. If used, it is set from
571 # inside a single Trio event loop. If used, it is set from
572 # `ipykernel.kernelapp`.
572 # `ipykernel.kernelapp`.
573 self.trio_runner = None
573 self.trio_runner = None
574
574
575 def get_ipython(self):
575 def get_ipython(self):
576 """Return the currently running IPython instance."""
576 """Return the currently running IPython instance."""
577 return self
577 return self
578
578
579 #-------------------------------------------------------------------------
579 #-------------------------------------------------------------------------
580 # Trait changed handlers
580 # Trait changed handlers
581 #-------------------------------------------------------------------------
581 #-------------------------------------------------------------------------
582 @observe('ipython_dir')
582 @observe('ipython_dir')
583 def _ipython_dir_changed(self, change):
583 def _ipython_dir_changed(self, change):
584 ensure_dir_exists(change['new'])
584 ensure_dir_exists(change['new'])
585
585
586 def set_autoindent(self,value=None):
586 def set_autoindent(self,value=None):
587 """Set the autoindent flag.
587 """Set the autoindent flag.
588
588
589 If called with no arguments, it acts as a toggle."""
589 If called with no arguments, it acts as a toggle."""
590 if value is None:
590 if value is None:
591 self.autoindent = not self.autoindent
591 self.autoindent = not self.autoindent
592 else:
592 else:
593 self.autoindent = value
593 self.autoindent = value
594
594
595 def set_trio_runner(self, tr):
595 def set_trio_runner(self, tr):
596 self.trio_runner = tr
596 self.trio_runner = tr
597
597
598 #-------------------------------------------------------------------------
598 #-------------------------------------------------------------------------
599 # init_* methods called by __init__
599 # init_* methods called by __init__
600 #-------------------------------------------------------------------------
600 #-------------------------------------------------------------------------
601
601
602 def init_ipython_dir(self, ipython_dir):
602 def init_ipython_dir(self, ipython_dir):
603 if ipython_dir is not None:
603 if ipython_dir is not None:
604 self.ipython_dir = ipython_dir
604 self.ipython_dir = ipython_dir
605 return
605 return
606
606
607 self.ipython_dir = get_ipython_dir()
607 self.ipython_dir = get_ipython_dir()
608
608
609 def init_profile_dir(self, profile_dir):
609 def init_profile_dir(self, profile_dir):
610 if profile_dir is not None:
610 if profile_dir is not None:
611 self.profile_dir = profile_dir
611 self.profile_dir = profile_dir
612 return
612 return
613 self.profile_dir = ProfileDir.create_profile_dir_by_name(
613 self.profile_dir = ProfileDir.create_profile_dir_by_name(
614 self.ipython_dir, "default"
614 self.ipython_dir, "default"
615 )
615 )
616
616
617 def init_instance_attrs(self):
617 def init_instance_attrs(self):
618 self.more = False
618 self.more = False
619
619
620 # command compiler
620 # command compiler
621 self.compile = self.compiler_class()
621 self.compile = self.compiler_class()
622
622
623 # Make an empty namespace, which extension writers can rely on both
623 # Make an empty namespace, which extension writers can rely on both
624 # existing and NEVER being used by ipython itself. This gives them a
624 # existing and NEVER being used by ipython itself. This gives them a
625 # convenient location for storing additional information and state
625 # convenient location for storing additional information and state
626 # their extensions may require, without fear of collisions with other
626 # their extensions may require, without fear of collisions with other
627 # ipython names that may develop later.
627 # ipython names that may develop later.
628 self.meta = Struct()
628 self.meta = Struct()
629
629
630 # Temporary files used for various purposes. Deleted at exit.
630 # Temporary files used for various purposes. Deleted at exit.
631 # The files here are stored with Path from Pathlib
631 # The files here are stored with Path from Pathlib
632 self.tempfiles = []
632 self.tempfiles = []
633 self.tempdirs = []
633 self.tempdirs = []
634
634
635 # keep track of where we started running (mainly for crash post-mortem)
635 # keep track of where we started running (mainly for crash post-mortem)
636 # This is not being used anywhere currently.
636 # This is not being used anywhere currently.
637 self.starting_dir = os.getcwd()
637 self.starting_dir = os.getcwd()
638
638
639 # Indentation management
639 # Indentation management
640 self.indent_current_nsp = 0
640 self.indent_current_nsp = 0
641
641
642 # Dict to track post-execution functions that have been registered
642 # Dict to track post-execution functions that have been registered
643 self._post_execute = {}
643 self._post_execute = {}
644
644
645 def init_environment(self):
645 def init_environment(self):
646 """Any changes we need to make to the user's environment."""
646 """Any changes we need to make to the user's environment."""
647 pass
647 pass
648
648
649 def init_encoding(self):
649 def init_encoding(self):
650 # Get system encoding at startup time. Certain terminals (like Emacs
650 # Get system encoding at startup time. Certain terminals (like Emacs
651 # under Win32 have it set to None, and we need to have a known valid
651 # under Win32 have it set to None, and we need to have a known valid
652 # encoding to use in the raw_input() method
652 # encoding to use in the raw_input() method
653 try:
653 try:
654 self.stdin_encoding = sys.stdin.encoding or 'ascii'
654 self.stdin_encoding = sys.stdin.encoding or 'ascii'
655 except AttributeError:
655 except AttributeError:
656 self.stdin_encoding = 'ascii'
656 self.stdin_encoding = 'ascii'
657
657
658
658
659 @observe('colors')
659 @observe('colors')
660 def init_syntax_highlighting(self, changes=None):
660 def init_syntax_highlighting(self, changes=None):
661 # Python source parser/formatter for syntax highlighting
661 # Python source parser/formatter for syntax highlighting
662 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
662 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
663 self.pycolorize = lambda src: pyformat(src,'str')
663 self.pycolorize = lambda src: pyformat(src,'str')
664
664
665 def refresh_style(self):
665 def refresh_style(self):
666 # No-op here, used in subclass
666 # No-op here, used in subclass
667 pass
667 pass
668
668
669 def init_pushd_popd_magic(self):
669 def init_pushd_popd_magic(self):
670 # for pushd/popd management
670 # for pushd/popd management
671 self.home_dir = get_home_dir()
671 self.home_dir = get_home_dir()
672
672
673 self.dir_stack = []
673 self.dir_stack = []
674
674
675 def init_logger(self):
675 def init_logger(self):
676 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
676 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
677 logmode='rotate')
677 logmode='rotate')
678
678
679 def init_logstart(self):
679 def init_logstart(self):
680 """Initialize logging in case it was requested at the command line.
680 """Initialize logging in case it was requested at the command line.
681 """
681 """
682 if self.logappend:
682 if self.logappend:
683 self.magic('logstart %s append' % self.logappend)
683 self.magic('logstart %s append' % self.logappend)
684 elif self.logfile:
684 elif self.logfile:
685 self.magic('logstart %s' % self.logfile)
685 self.magic('logstart %s' % self.logfile)
686 elif self.logstart:
686 elif self.logstart:
687 self.magic('logstart')
687 self.magic('logstart')
688
688
689
689
690 def init_builtins(self):
690 def init_builtins(self):
691 # A single, static flag that we set to True. Its presence indicates
691 # A single, static flag that we set to True. Its presence indicates
692 # that an IPython shell has been created, and we make no attempts at
692 # that an IPython shell has been created, and we make no attempts at
693 # removing on exit or representing the existence of more than one
693 # removing on exit or representing the existence of more than one
694 # IPython at a time.
694 # IPython at a time.
695 builtin_mod.__dict__['__IPYTHON__'] = True
695 builtin_mod.__dict__['__IPYTHON__'] = True
696 builtin_mod.__dict__['display'] = display
696 builtin_mod.__dict__['display'] = display
697
697
698 self.builtin_trap = BuiltinTrap(shell=self)
698 self.builtin_trap = BuiltinTrap(shell=self)
699
699
700 @observe('colors')
700 @observe('colors')
701 def init_inspector(self, changes=None):
701 def init_inspector(self, changes=None):
702 # Object inspector
702 # Object inspector
703 self.inspector = oinspect.Inspector(oinspect.InspectColors,
703 self.inspector = oinspect.Inspector(oinspect.InspectColors,
704 PyColorize.ANSICodeColors,
704 PyColorize.ANSICodeColors,
705 self.colors,
705 self.colors,
706 self.object_info_string_level)
706 self.object_info_string_level)
707
707
708 def init_io(self):
708 def init_io(self):
709 # implemented in subclasses, TerminalInteractiveShell does call
709 # implemented in subclasses, TerminalInteractiveShell does call
710 # colorama.init().
710 # colorama.init().
711 pass
711 pass
712
712
713 def init_prompts(self):
713 def init_prompts(self):
714 # Set system prompts, so that scripts can decide if they are running
714 # Set system prompts, so that scripts can decide if they are running
715 # interactively.
715 # interactively.
716 sys.ps1 = 'In : '
716 sys.ps1 = 'In : '
717 sys.ps2 = '...: '
717 sys.ps2 = '...: '
718 sys.ps3 = 'Out: '
718 sys.ps3 = 'Out: '
719
719
720 def init_display_formatter(self):
720 def init_display_formatter(self):
721 self.display_formatter = DisplayFormatter(parent=self)
721 self.display_formatter = DisplayFormatter(parent=self)
722 self.configurables.append(self.display_formatter)
722 self.configurables.append(self.display_formatter)
723
723
724 def init_display_pub(self):
724 def init_display_pub(self):
725 self.display_pub = self.display_pub_class(parent=self, shell=self)
725 self.display_pub = self.display_pub_class(parent=self, shell=self)
726 self.configurables.append(self.display_pub)
726 self.configurables.append(self.display_pub)
727
727
728 def init_data_pub(self):
728 def init_data_pub(self):
729 if not self.data_pub_class:
729 if not self.data_pub_class:
730 self.data_pub = None
730 self.data_pub = None
731 return
731 return
732 self.data_pub = self.data_pub_class(parent=self)
732 self.data_pub = self.data_pub_class(parent=self)
733 self.configurables.append(self.data_pub)
733 self.configurables.append(self.data_pub)
734
734
735 def init_displayhook(self):
735 def init_displayhook(self):
736 # Initialize displayhook, set in/out prompts and printing system
736 # Initialize displayhook, set in/out prompts and printing system
737 self.displayhook = self.displayhook_class(
737 self.displayhook = self.displayhook_class(
738 parent=self,
738 parent=self,
739 shell=self,
739 shell=self,
740 cache_size=self.cache_size,
740 cache_size=self.cache_size,
741 )
741 )
742 self.configurables.append(self.displayhook)
742 self.configurables.append(self.displayhook)
743 # This is a context manager that installs/revmoes the displayhook at
743 # This is a context manager that installs/revmoes the displayhook at
744 # the appropriate time.
744 # the appropriate time.
745 self.display_trap = DisplayTrap(hook=self.displayhook)
745 self.display_trap = DisplayTrap(hook=self.displayhook)
746
746
747 def init_virtualenv(self):
747 def init_virtualenv(self):
748 """Add the current virtualenv to sys.path so the user can import modules from it.
748 """Add the current virtualenv to sys.path so the user can import modules from it.
749 This isn't perfect: it doesn't use the Python interpreter with which the
749 This isn't perfect: it doesn't use the Python interpreter with which the
750 virtualenv was built, and it ignores the --no-site-packages option. A
750 virtualenv was built, and it ignores the --no-site-packages option. A
751 warning will appear suggesting the user installs IPython in the
751 warning will appear suggesting the user installs IPython in the
752 virtualenv, but for many cases, it probably works well enough.
752 virtualenv, but for many cases, it probably works well enough.
753
753
754 Adapted from code snippets online.
754 Adapted from code snippets online.
755
755
756 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
756 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
757 """
757 """
758 if 'VIRTUAL_ENV' not in os.environ:
758 if 'VIRTUAL_ENV' not in os.environ:
759 # Not in a virtualenv
759 # Not in a virtualenv
760 return
760 return
761 elif os.environ["VIRTUAL_ENV"] == "":
761 elif os.environ["VIRTUAL_ENV"] == "":
762 warn("Virtual env path set to '', please check if this is intended.")
762 warn("Virtual env path set to '', please check if this is intended.")
763 return
763 return
764
764
765 p = Path(sys.executable)
765 p = Path(sys.executable)
766 p_venv = Path(os.environ["VIRTUAL_ENV"])
766 p_venv = Path(os.environ["VIRTUAL_ENV"])
767
767
768 # fallback venv detection:
768 # fallback venv detection:
769 # stdlib venv may symlink sys.executable, so we can't use realpath.
769 # stdlib venv may symlink sys.executable, so we can't use realpath.
770 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
770 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
771 # So we just check every item in the symlink tree (generally <= 3)
771 # So we just check every item in the symlink tree (generally <= 3)
772 paths = [p]
772 paths = [p]
773 while p.is_symlink():
773 while p.is_symlink():
774 p = Path(os.readlink(p))
774 p = Path(os.readlink(p))
775 paths.append(p.resolve())
775 paths.append(p.resolve())
776
776
777 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
777 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
778 if p_venv.parts[1] == "cygdrive":
778 if p_venv.parts[1] == "cygdrive":
779 drive_name = p_venv.parts[2]
779 drive_name = p_venv.parts[2]
780 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
780 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
781
781
782 if any(p_venv == p.parents[1] for p in paths):
782 if any(p_venv == p.parents[1] for p in paths):
783 # Our exe is inside or has access to the virtualenv, don't need to do anything.
783 # Our exe is inside or has access to the virtualenv, don't need to do anything.
784 return
784 return
785
785
786 if sys.platform == "win32":
786 if sys.platform == "win32":
787 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
787 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
788 else:
788 else:
789 virtual_env_path = Path(
789 virtual_env_path = Path(
790 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
790 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
791 )
791 )
792 p_ver = sys.version_info[:2]
792 p_ver = sys.version_info[:2]
793
793
794 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
794 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
795 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
795 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
796 if re_m:
796 if re_m:
797 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
797 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
798 if predicted_path.exists():
798 if predicted_path.exists():
799 p_ver = re_m.groups()
799 p_ver = re_m.groups()
800
800
801 virtual_env = str(virtual_env_path).format(*p_ver)
801 virtual_env = str(virtual_env_path).format(*p_ver)
802
802
803 warn(
803 warn(
804 "Attempting to work in a virtualenv. If you encounter problems, "
804 "Attempting to work in a virtualenv. If you encounter problems, "
805 "please install IPython inside the virtualenv."
805 "please install IPython inside the virtualenv."
806 )
806 )
807 import site
807 import site
808 sys.path.insert(0, virtual_env)
808 sys.path.insert(0, virtual_env)
809 site.addsitedir(virtual_env)
809 site.addsitedir(virtual_env)
810
810
811 #-------------------------------------------------------------------------
811 #-------------------------------------------------------------------------
812 # Things related to injections into the sys module
812 # Things related to injections into the sys module
813 #-------------------------------------------------------------------------
813 #-------------------------------------------------------------------------
814
814
815 def save_sys_module_state(self):
815 def save_sys_module_state(self):
816 """Save the state of hooks in the sys module.
816 """Save the state of hooks in the sys module.
817
817
818 This has to be called after self.user_module is created.
818 This has to be called after self.user_module is created.
819 """
819 """
820 self._orig_sys_module_state = {'stdin': sys.stdin,
820 self._orig_sys_module_state = {'stdin': sys.stdin,
821 'stdout': sys.stdout,
821 'stdout': sys.stdout,
822 'stderr': sys.stderr,
822 'stderr': sys.stderr,
823 'excepthook': sys.excepthook}
823 'excepthook': sys.excepthook}
824 self._orig_sys_modules_main_name = self.user_module.__name__
824 self._orig_sys_modules_main_name = self.user_module.__name__
825 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
825 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
826
826
827 def restore_sys_module_state(self):
827 def restore_sys_module_state(self):
828 """Restore the state of the sys module."""
828 """Restore the state of the sys module."""
829 try:
829 try:
830 for k, v in self._orig_sys_module_state.items():
830 for k, v in self._orig_sys_module_state.items():
831 setattr(sys, k, v)
831 setattr(sys, k, v)
832 except AttributeError:
832 except AttributeError:
833 pass
833 pass
834 # Reset what what done in self.init_sys_modules
834 # Reset what what done in self.init_sys_modules
835 if self._orig_sys_modules_main_mod is not None:
835 if self._orig_sys_modules_main_mod is not None:
836 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
836 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
837
837
838 #-------------------------------------------------------------------------
838 #-------------------------------------------------------------------------
839 # Things related to the banner
839 # Things related to the banner
840 #-------------------------------------------------------------------------
840 #-------------------------------------------------------------------------
841
841
842 @property
842 @property
843 def banner(self):
843 def banner(self):
844 banner = self.banner1
844 banner = self.banner1
845 if self.profile and self.profile != 'default':
845 if self.profile and self.profile != 'default':
846 banner += '\nIPython profile: %s\n' % self.profile
846 banner += '\nIPython profile: %s\n' % self.profile
847 if self.banner2:
847 if self.banner2:
848 banner += '\n' + self.banner2
848 banner += '\n' + self.banner2
849 return banner
849 return banner
850
850
851 def show_banner(self, banner=None):
851 def show_banner(self, banner=None):
852 if banner is None:
852 if banner is None:
853 banner = self.banner
853 banner = self.banner
854 sys.stdout.write(banner)
854 sys.stdout.write(banner)
855
855
856 #-------------------------------------------------------------------------
856 #-------------------------------------------------------------------------
857 # Things related to hooks
857 # Things related to hooks
858 #-------------------------------------------------------------------------
858 #-------------------------------------------------------------------------
859
859
860 def init_hooks(self):
860 def init_hooks(self):
861 # hooks holds pointers used for user-side customizations
861 # hooks holds pointers used for user-side customizations
862 self.hooks = Struct()
862 self.hooks = Struct()
863
863
864 self.strdispatchers = {}
864 self.strdispatchers = {}
865
865
866 # Set all default hooks, defined in the IPython.hooks module.
866 # Set all default hooks, defined in the IPython.hooks module.
867 hooks = IPython.core.hooks
867 hooks = IPython.core.hooks
868 for hook_name in hooks.__all__:
868 for hook_name in hooks.__all__:
869 # default hooks have priority 100, i.e. low; user hooks should have
869 # default hooks have priority 100, i.e. low; user hooks should have
870 # 0-100 priority
870 # 0-100 priority
871 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
871 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
872
872
873 if self.display_page:
873 if self.display_page:
874 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
874 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
875
875
876 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
876 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
877 _warn_deprecated=True):
877 _warn_deprecated=True):
878 """set_hook(name,hook) -> sets an internal IPython hook.
878 """set_hook(name,hook) -> sets an internal IPython hook.
879
879
880 IPython exposes some of its internal API as user-modifiable hooks. By
880 IPython exposes some of its internal API as user-modifiable hooks. By
881 adding your function to one of these hooks, you can modify IPython's
881 adding your function to one of these hooks, you can modify IPython's
882 behavior to call at runtime your own routines."""
882 behavior to call at runtime your own routines."""
883
883
884 # At some point in the future, this should validate the hook before it
884 # At some point in the future, this should validate the hook before it
885 # accepts it. Probably at least check that the hook takes the number
885 # accepts it. Probably at least check that the hook takes the number
886 # of args it's supposed to.
886 # of args it's supposed to.
887
887
888 f = types.MethodType(hook,self)
888 f = types.MethodType(hook,self)
889
889
890 # check if the hook is for strdispatcher first
890 # check if the hook is for strdispatcher first
891 if str_key is not None:
891 if str_key is not None:
892 sdp = self.strdispatchers.get(name, StrDispatch())
892 sdp = self.strdispatchers.get(name, StrDispatch())
893 sdp.add_s(str_key, f, priority )
893 sdp.add_s(str_key, f, priority )
894 self.strdispatchers[name] = sdp
894 self.strdispatchers[name] = sdp
895 return
895 return
896 if re_key is not None:
896 if re_key is not None:
897 sdp = self.strdispatchers.get(name, StrDispatch())
897 sdp = self.strdispatchers.get(name, StrDispatch())
898 sdp.add_re(re.compile(re_key), f, priority )
898 sdp.add_re(re.compile(re_key), f, priority )
899 self.strdispatchers[name] = sdp
899 self.strdispatchers[name] = sdp
900 return
900 return
901
901
902 dp = getattr(self.hooks, name, None)
902 dp = getattr(self.hooks, name, None)
903 if name not in IPython.core.hooks.__all__:
903 if name not in IPython.core.hooks.__all__:
904 print("Warning! Hook '%s' is not one of %s" % \
904 print("Warning! Hook '%s' is not one of %s" % \
905 (name, IPython.core.hooks.__all__ ))
905 (name, IPython.core.hooks.__all__ ))
906
906
907 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
907 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
908 alternative = IPython.core.hooks.deprecated[name]
908 alternative = IPython.core.hooks.deprecated[name]
909 raise ValueError(
909 raise ValueError(
910 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
910 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
911 name, alternative
911 name, alternative
912 )
912 )
913 )
913 )
914
914
915 if not dp:
915 if not dp:
916 dp = IPython.core.hooks.CommandChainDispatcher()
916 dp = IPython.core.hooks.CommandChainDispatcher()
917
917
918 try:
918 try:
919 dp.add(f,priority)
919 dp.add(f,priority)
920 except AttributeError:
920 except AttributeError:
921 # it was not commandchain, plain old func - replace
921 # it was not commandchain, plain old func - replace
922 dp = f
922 dp = f
923
923
924 setattr(self.hooks,name, dp)
924 setattr(self.hooks,name, dp)
925
925
926 #-------------------------------------------------------------------------
926 #-------------------------------------------------------------------------
927 # Things related to events
927 # Things related to events
928 #-------------------------------------------------------------------------
928 #-------------------------------------------------------------------------
929
929
930 def init_events(self):
930 def init_events(self):
931 self.events = EventManager(self, available_events)
931 self.events = EventManager(self, available_events)
932
932
933 self.events.register("pre_execute", self._clear_warning_registry)
933 self.events.register("pre_execute", self._clear_warning_registry)
934
934
935 def register_post_execute(self, func):
935 def register_post_execute(self, func):
936 """DEPRECATED: Use ip.events.register('post_run_cell', func)
936 """DEPRECATED: Use ip.events.register('post_run_cell', func)
937
937
938 Register a function for calling after code execution.
938 Register a function for calling after code execution.
939 """
939 """
940 raise ValueError(
940 raise ValueError(
941 "ip.register_post_execute is deprecated since IPython 1.0, use "
941 "ip.register_post_execute is deprecated since IPython 1.0, use "
942 "ip.events.register('post_run_cell', func) instead."
942 "ip.events.register('post_run_cell', func) instead."
943 )
943 )
944
944
945 def _clear_warning_registry(self):
945 def _clear_warning_registry(self):
946 # clear the warning registry, so that different code blocks with
946 # clear the warning registry, so that different code blocks with
947 # overlapping line number ranges don't cause spurious suppression of
947 # overlapping line number ranges don't cause spurious suppression of
948 # warnings (see gh-6611 for details)
948 # warnings (see gh-6611 for details)
949 if "__warningregistry__" in self.user_global_ns:
949 if "__warningregistry__" in self.user_global_ns:
950 del self.user_global_ns["__warningregistry__"]
950 del self.user_global_ns["__warningregistry__"]
951
951
952 #-------------------------------------------------------------------------
952 #-------------------------------------------------------------------------
953 # Things related to the "main" module
953 # Things related to the "main" module
954 #-------------------------------------------------------------------------
954 #-------------------------------------------------------------------------
955
955
956 def new_main_mod(self, filename, modname):
956 def new_main_mod(self, filename, modname):
957 """Return a new 'main' module object for user code execution.
957 """Return a new 'main' module object for user code execution.
958
958
959 ``filename`` should be the path of the script which will be run in the
959 ``filename`` should be the path of the script which will be run in the
960 module. Requests with the same filename will get the same module, with
960 module. Requests with the same filename will get the same module, with
961 its namespace cleared.
961 its namespace cleared.
962
962
963 ``modname`` should be the module name - normally either '__main__' or
963 ``modname`` should be the module name - normally either '__main__' or
964 the basename of the file without the extension.
964 the basename of the file without the extension.
965
965
966 When scripts are executed via %run, we must keep a reference to their
966 When scripts are executed via %run, we must keep a reference to their
967 __main__ module around so that Python doesn't
967 __main__ module around so that Python doesn't
968 clear it, rendering references to module globals useless.
968 clear it, rendering references to module globals useless.
969
969
970 This method keeps said reference in a private dict, keyed by the
970 This method keeps said reference in a private dict, keyed by the
971 absolute path of the script. This way, for multiple executions of the
971 absolute path of the script. This way, for multiple executions of the
972 same script we only keep one copy of the namespace (the last one),
972 same script we only keep one copy of the namespace (the last one),
973 thus preventing memory leaks from old references while allowing the
973 thus preventing memory leaks from old references while allowing the
974 objects from the last execution to be accessible.
974 objects from the last execution to be accessible.
975 """
975 """
976 filename = os.path.abspath(filename)
976 filename = os.path.abspath(filename)
977 try:
977 try:
978 main_mod = self._main_mod_cache[filename]
978 main_mod = self._main_mod_cache[filename]
979 except KeyError:
979 except KeyError:
980 main_mod = self._main_mod_cache[filename] = types.ModuleType(
980 main_mod = self._main_mod_cache[filename] = types.ModuleType(
981 modname,
981 modname,
982 doc="Module created for script run in IPython")
982 doc="Module created for script run in IPython")
983 else:
983 else:
984 main_mod.__dict__.clear()
984 main_mod.__dict__.clear()
985 main_mod.__name__ = modname
985 main_mod.__name__ = modname
986
986
987 main_mod.__file__ = filename
987 main_mod.__file__ = filename
988 # It seems pydoc (and perhaps others) needs any module instance to
988 # It seems pydoc (and perhaps others) needs any module instance to
989 # implement a __nonzero__ method
989 # implement a __nonzero__ method
990 main_mod.__nonzero__ = lambda : True
990 main_mod.__nonzero__ = lambda : True
991
991
992 return main_mod
992 return main_mod
993
993
994 def clear_main_mod_cache(self):
994 def clear_main_mod_cache(self):
995 """Clear the cache of main modules.
995 """Clear the cache of main modules.
996
996
997 Mainly for use by utilities like %reset.
997 Mainly for use by utilities like %reset.
998
998
999 Examples
999 Examples
1000 --------
1000 --------
1001 In [15]: import IPython
1001 In [15]: import IPython
1002
1002
1003 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1003 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1004
1004
1005 In [17]: len(_ip._main_mod_cache) > 0
1005 In [17]: len(_ip._main_mod_cache) > 0
1006 Out[17]: True
1006 Out[17]: True
1007
1007
1008 In [18]: _ip.clear_main_mod_cache()
1008 In [18]: _ip.clear_main_mod_cache()
1009
1009
1010 In [19]: len(_ip._main_mod_cache) == 0
1010 In [19]: len(_ip._main_mod_cache) == 0
1011 Out[19]: True
1011 Out[19]: True
1012 """
1012 """
1013 self._main_mod_cache.clear()
1013 self._main_mod_cache.clear()
1014
1014
1015 #-------------------------------------------------------------------------
1015 #-------------------------------------------------------------------------
1016 # Things related to debugging
1016 # Things related to debugging
1017 #-------------------------------------------------------------------------
1017 #-------------------------------------------------------------------------
1018
1018
1019 def init_pdb(self):
1019 def init_pdb(self):
1020 # Set calling of pdb on exceptions
1020 # Set calling of pdb on exceptions
1021 # self.call_pdb is a property
1021 # self.call_pdb is a property
1022 self.call_pdb = self.pdb
1022 self.call_pdb = self.pdb
1023
1023
1024 def _get_call_pdb(self):
1024 def _get_call_pdb(self):
1025 return self._call_pdb
1025 return self._call_pdb
1026
1026
1027 def _set_call_pdb(self,val):
1027 def _set_call_pdb(self,val):
1028
1028
1029 if val not in (0,1,False,True):
1029 if val not in (0,1,False,True):
1030 raise ValueError('new call_pdb value must be boolean')
1030 raise ValueError('new call_pdb value must be boolean')
1031
1031
1032 # store value in instance
1032 # store value in instance
1033 self._call_pdb = val
1033 self._call_pdb = val
1034
1034
1035 # notify the actual exception handlers
1035 # notify the actual exception handlers
1036 self.InteractiveTB.call_pdb = val
1036 self.InteractiveTB.call_pdb = val
1037
1037
1038 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1038 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1039 'Control auto-activation of pdb at exceptions')
1039 'Control auto-activation of pdb at exceptions')
1040
1040
1041 def debugger(self,force=False):
1041 def debugger(self,force=False):
1042 """Call the pdb debugger.
1042 """Call the pdb debugger.
1043
1043
1044 Keywords:
1044 Keywords:
1045
1045
1046 - force(False): by default, this routine checks the instance call_pdb
1046 - force(False): by default, this routine checks the instance call_pdb
1047 flag and does not actually invoke the debugger if the flag is false.
1047 flag and does not actually invoke the debugger if the flag is false.
1048 The 'force' option forces the debugger to activate even if the flag
1048 The 'force' option forces the debugger to activate even if the flag
1049 is false.
1049 is false.
1050 """
1050 """
1051
1051
1052 if not (force or self.call_pdb):
1052 if not (force or self.call_pdb):
1053 return
1053 return
1054
1054
1055 if not hasattr(sys,'last_traceback'):
1055 if not hasattr(sys,'last_traceback'):
1056 error('No traceback has been produced, nothing to debug.')
1056 error('No traceback has been produced, nothing to debug.')
1057 return
1057 return
1058
1058
1059 self.InteractiveTB.debugger(force=True)
1059 self.InteractiveTB.debugger(force=True)
1060
1060
1061 #-------------------------------------------------------------------------
1061 #-------------------------------------------------------------------------
1062 # Things related to IPython's various namespaces
1062 # Things related to IPython's various namespaces
1063 #-------------------------------------------------------------------------
1063 #-------------------------------------------------------------------------
1064 default_user_namespaces = True
1064 default_user_namespaces = True
1065
1065
1066 def init_create_namespaces(self, user_module=None, user_ns=None):
1066 def init_create_namespaces(self, user_module=None, user_ns=None):
1067 # Create the namespace where the user will operate. user_ns is
1067 # Create the namespace where the user will operate. user_ns is
1068 # normally the only one used, and it is passed to the exec calls as
1068 # normally the only one used, and it is passed to the exec calls as
1069 # the locals argument. But we do carry a user_global_ns namespace
1069 # the locals argument. But we do carry a user_global_ns namespace
1070 # given as the exec 'globals' argument, This is useful in embedding
1070 # given as the exec 'globals' argument, This is useful in embedding
1071 # situations where the ipython shell opens in a context where the
1071 # situations where the ipython shell opens in a context where the
1072 # distinction between locals and globals is meaningful. For
1072 # distinction between locals and globals is meaningful. For
1073 # non-embedded contexts, it is just the same object as the user_ns dict.
1073 # non-embedded contexts, it is just the same object as the user_ns dict.
1074
1074
1075 # FIXME. For some strange reason, __builtins__ is showing up at user
1075 # FIXME. For some strange reason, __builtins__ is showing up at user
1076 # level as a dict instead of a module. This is a manual fix, but I
1076 # level as a dict instead of a module. This is a manual fix, but I
1077 # should really track down where the problem is coming from. Alex
1077 # should really track down where the problem is coming from. Alex
1078 # Schmolck reported this problem first.
1078 # Schmolck reported this problem first.
1079
1079
1080 # A useful post by Alex Martelli on this topic:
1080 # A useful post by Alex Martelli on this topic:
1081 # Re: inconsistent value from __builtins__
1081 # Re: inconsistent value from __builtins__
1082 # Von: Alex Martelli <aleaxit@yahoo.com>
1082 # Von: Alex Martelli <aleaxit@yahoo.com>
1083 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1083 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1084 # Gruppen: comp.lang.python
1084 # Gruppen: comp.lang.python
1085
1085
1086 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1086 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1087 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1087 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1088 # > <type 'dict'>
1088 # > <type 'dict'>
1089 # > >>> print type(__builtins__)
1089 # > >>> print type(__builtins__)
1090 # > <type 'module'>
1090 # > <type 'module'>
1091 # > Is this difference in return value intentional?
1091 # > Is this difference in return value intentional?
1092
1092
1093 # Well, it's documented that '__builtins__' can be either a dictionary
1093 # Well, it's documented that '__builtins__' can be either a dictionary
1094 # or a module, and it's been that way for a long time. Whether it's
1094 # or a module, and it's been that way for a long time. Whether it's
1095 # intentional (or sensible), I don't know. In any case, the idea is
1095 # intentional (or sensible), I don't know. In any case, the idea is
1096 # that if you need to access the built-in namespace directly, you
1096 # that if you need to access the built-in namespace directly, you
1097 # should start with "import __builtin__" (note, no 's') which will
1097 # should start with "import __builtin__" (note, no 's') which will
1098 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1098 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1099
1099
1100 # These routines return a properly built module and dict as needed by
1100 # These routines return a properly built module and dict as needed by
1101 # the rest of the code, and can also be used by extension writers to
1101 # the rest of the code, and can also be used by extension writers to
1102 # generate properly initialized namespaces.
1102 # generate properly initialized namespaces.
1103 if (user_ns is not None) or (user_module is not None):
1103 if (user_ns is not None) or (user_module is not None):
1104 self.default_user_namespaces = False
1104 self.default_user_namespaces = False
1105 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1105 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1106
1106
1107 # A record of hidden variables we have added to the user namespace, so
1107 # A record of hidden variables we have added to the user namespace, so
1108 # we can list later only variables defined in actual interactive use.
1108 # we can list later only variables defined in actual interactive use.
1109 self.user_ns_hidden = {}
1109 self.user_ns_hidden = {}
1110
1110
1111 # Now that FakeModule produces a real module, we've run into a nasty
1111 # Now that FakeModule produces a real module, we've run into a nasty
1112 # problem: after script execution (via %run), the module where the user
1112 # problem: after script execution (via %run), the module where the user
1113 # code ran is deleted. Now that this object is a true module (needed
1113 # code ran is deleted. Now that this object is a true module (needed
1114 # so doctest and other tools work correctly), the Python module
1114 # so doctest and other tools work correctly), the Python module
1115 # teardown mechanism runs over it, and sets to None every variable
1115 # teardown mechanism runs over it, and sets to None every variable
1116 # present in that module. Top-level references to objects from the
1116 # present in that module. Top-level references to objects from the
1117 # script survive, because the user_ns is updated with them. However,
1117 # script survive, because the user_ns is updated with them. However,
1118 # calling functions defined in the script that use other things from
1118 # calling functions defined in the script that use other things from
1119 # the script will fail, because the function's closure had references
1119 # the script will fail, because the function's closure had references
1120 # to the original objects, which are now all None. So we must protect
1120 # to the original objects, which are now all None. So we must protect
1121 # these modules from deletion by keeping a cache.
1121 # these modules from deletion by keeping a cache.
1122 #
1122 #
1123 # To avoid keeping stale modules around (we only need the one from the
1123 # To avoid keeping stale modules around (we only need the one from the
1124 # last run), we use a dict keyed with the full path to the script, so
1124 # last run), we use a dict keyed with the full path to the script, so
1125 # only the last version of the module is held in the cache. Note,
1125 # only the last version of the module is held in the cache. Note,
1126 # however, that we must cache the module *namespace contents* (their
1126 # however, that we must cache the module *namespace contents* (their
1127 # __dict__). Because if we try to cache the actual modules, old ones
1127 # __dict__). Because if we try to cache the actual modules, old ones
1128 # (uncached) could be destroyed while still holding references (such as
1128 # (uncached) could be destroyed while still holding references (such as
1129 # those held by GUI objects that tend to be long-lived)>
1129 # those held by GUI objects that tend to be long-lived)>
1130 #
1130 #
1131 # The %reset command will flush this cache. See the cache_main_mod()
1131 # The %reset command will flush this cache. See the cache_main_mod()
1132 # and clear_main_mod_cache() methods for details on use.
1132 # and clear_main_mod_cache() methods for details on use.
1133
1133
1134 # This is the cache used for 'main' namespaces
1134 # This is the cache used for 'main' namespaces
1135 self._main_mod_cache = {}
1135 self._main_mod_cache = {}
1136
1136
1137 # A table holding all the namespaces IPython deals with, so that
1137 # A table holding all the namespaces IPython deals with, so that
1138 # introspection facilities can search easily.
1138 # introspection facilities can search easily.
1139 self.ns_table = {'user_global':self.user_module.__dict__,
1139 self.ns_table = {'user_global':self.user_module.__dict__,
1140 'user_local':self.user_ns,
1140 'user_local':self.user_ns,
1141 'builtin':builtin_mod.__dict__
1141 'builtin':builtin_mod.__dict__
1142 }
1142 }
1143
1143
1144 @property
1144 @property
1145 def user_global_ns(self):
1145 def user_global_ns(self):
1146 return self.user_module.__dict__
1146 return self.user_module.__dict__
1147
1147
1148 def prepare_user_module(self, user_module=None, user_ns=None):
1148 def prepare_user_module(self, user_module=None, user_ns=None):
1149 """Prepare the module and namespace in which user code will be run.
1149 """Prepare the module and namespace in which user code will be run.
1150
1150
1151 When IPython is started normally, both parameters are None: a new module
1151 When IPython is started normally, both parameters are None: a new module
1152 is created automatically, and its __dict__ used as the namespace.
1152 is created automatically, and its __dict__ used as the namespace.
1153
1153
1154 If only user_module is provided, its __dict__ is used as the namespace.
1154 If only user_module is provided, its __dict__ is used as the namespace.
1155 If only user_ns is provided, a dummy module is created, and user_ns
1155 If only user_ns is provided, a dummy module is created, and user_ns
1156 becomes the global namespace. If both are provided (as they may be
1156 becomes the global namespace. If both are provided (as they may be
1157 when embedding), user_ns is the local namespace, and user_module
1157 when embedding), user_ns is the local namespace, and user_module
1158 provides the global namespace.
1158 provides the global namespace.
1159
1159
1160 Parameters
1160 Parameters
1161 ----------
1161 ----------
1162 user_module : module, optional
1162 user_module : module, optional
1163 The current user module in which IPython is being run. If None,
1163 The current user module in which IPython is being run. If None,
1164 a clean module will be created.
1164 a clean module will be created.
1165 user_ns : dict, optional
1165 user_ns : dict, optional
1166 A namespace in which to run interactive commands.
1166 A namespace in which to run interactive commands.
1167
1167
1168 Returns
1168 Returns
1169 -------
1169 -------
1170 A tuple of user_module and user_ns, each properly initialised.
1170 A tuple of user_module and user_ns, each properly initialised.
1171 """
1171 """
1172 if user_module is None and user_ns is not None:
1172 if user_module is None and user_ns is not None:
1173 user_ns.setdefault("__name__", "__main__")
1173 user_ns.setdefault("__name__", "__main__")
1174 user_module = DummyMod()
1174 user_module = DummyMod()
1175 user_module.__dict__ = user_ns
1175 user_module.__dict__ = user_ns
1176
1176
1177 if user_module is None:
1177 if user_module is None:
1178 user_module = types.ModuleType("__main__",
1178 user_module = types.ModuleType("__main__",
1179 doc="Automatically created module for IPython interactive environment")
1179 doc="Automatically created module for IPython interactive environment")
1180
1180
1181 # We must ensure that __builtin__ (without the final 's') is always
1181 # We must ensure that __builtin__ (without the final 's') is always
1182 # available and pointing to the __builtin__ *module*. For more details:
1182 # available and pointing to the __builtin__ *module*. For more details:
1183 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1183 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1184 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1184 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1185 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1185 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1186
1186
1187 if user_ns is None:
1187 if user_ns is None:
1188 user_ns = user_module.__dict__
1188 user_ns = user_module.__dict__
1189
1189
1190 return user_module, user_ns
1190 return user_module, user_ns
1191
1191
1192 def init_sys_modules(self):
1192 def init_sys_modules(self):
1193 # We need to insert into sys.modules something that looks like a
1193 # We need to insert into sys.modules something that looks like a
1194 # module but which accesses the IPython namespace, for shelve and
1194 # module but which accesses the IPython namespace, for shelve and
1195 # pickle to work interactively. Normally they rely on getting
1195 # pickle to work interactively. Normally they rely on getting
1196 # everything out of __main__, but for embedding purposes each IPython
1196 # everything out of __main__, but for embedding purposes each IPython
1197 # instance has its own private namespace, so we can't go shoving
1197 # instance has its own private namespace, so we can't go shoving
1198 # everything into __main__.
1198 # everything into __main__.
1199
1199
1200 # note, however, that we should only do this for non-embedded
1200 # note, however, that we should only do this for non-embedded
1201 # ipythons, which really mimic the __main__.__dict__ with their own
1201 # ipythons, which really mimic the __main__.__dict__ with their own
1202 # namespace. Embedded instances, on the other hand, should not do
1202 # namespace. Embedded instances, on the other hand, should not do
1203 # this because they need to manage the user local/global namespaces
1203 # this because they need to manage the user local/global namespaces
1204 # only, but they live within a 'normal' __main__ (meaning, they
1204 # only, but they live within a 'normal' __main__ (meaning, they
1205 # shouldn't overtake the execution environment of the script they're
1205 # shouldn't overtake the execution environment of the script they're
1206 # embedded in).
1206 # embedded in).
1207
1207
1208 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1208 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1209 main_name = self.user_module.__name__
1209 main_name = self.user_module.__name__
1210 sys.modules[main_name] = self.user_module
1210 sys.modules[main_name] = self.user_module
1211
1211
1212 def init_user_ns(self):
1212 def init_user_ns(self):
1213 """Initialize all user-visible namespaces to their minimum defaults.
1213 """Initialize all user-visible namespaces to their minimum defaults.
1214
1214
1215 Certain history lists are also initialized here, as they effectively
1215 Certain history lists are also initialized here, as they effectively
1216 act as user namespaces.
1216 act as user namespaces.
1217
1217
1218 Notes
1218 Notes
1219 -----
1219 -----
1220 All data structures here are only filled in, they are NOT reset by this
1220 All data structures here are only filled in, they are NOT reset by this
1221 method. If they were not empty before, data will simply be added to
1221 method. If they were not empty before, data will simply be added to
1222 them.
1222 them.
1223 """
1223 """
1224 # This function works in two parts: first we put a few things in
1224 # This function works in two parts: first we put a few things in
1225 # user_ns, and we sync that contents into user_ns_hidden so that these
1225 # user_ns, and we sync that contents into user_ns_hidden so that these
1226 # initial variables aren't shown by %who. After the sync, we add the
1226 # initial variables aren't shown by %who. After the sync, we add the
1227 # rest of what we *do* want the user to see with %who even on a new
1227 # rest of what we *do* want the user to see with %who even on a new
1228 # session (probably nothing, so they really only see their own stuff)
1228 # session (probably nothing, so they really only see their own stuff)
1229
1229
1230 # The user dict must *always* have a __builtin__ reference to the
1230 # The user dict must *always* have a __builtin__ reference to the
1231 # Python standard __builtin__ namespace, which must be imported.
1231 # Python standard __builtin__ namespace, which must be imported.
1232 # This is so that certain operations in prompt evaluation can be
1232 # This is so that certain operations in prompt evaluation can be
1233 # reliably executed with builtins. Note that we can NOT use
1233 # reliably executed with builtins. Note that we can NOT use
1234 # __builtins__ (note the 's'), because that can either be a dict or a
1234 # __builtins__ (note the 's'), because that can either be a dict or a
1235 # module, and can even mutate at runtime, depending on the context
1235 # module, and can even mutate at runtime, depending on the context
1236 # (Python makes no guarantees on it). In contrast, __builtin__ is
1236 # (Python makes no guarantees on it). In contrast, __builtin__ is
1237 # always a module object, though it must be explicitly imported.
1237 # always a module object, though it must be explicitly imported.
1238
1238
1239 # For more details:
1239 # For more details:
1240 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1240 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1241 ns = {}
1241 ns = {}
1242
1242
1243 # make global variables for user access to the histories
1243 # make global variables for user access to the histories
1244 ns['_ih'] = self.history_manager.input_hist_parsed
1244 ns['_ih'] = self.history_manager.input_hist_parsed
1245 ns['_oh'] = self.history_manager.output_hist
1245 ns['_oh'] = self.history_manager.output_hist
1246 ns['_dh'] = self.history_manager.dir_hist
1246 ns['_dh'] = self.history_manager.dir_hist
1247
1247
1248 # user aliases to input and output histories. These shouldn't show up
1248 # user aliases to input and output histories. These shouldn't show up
1249 # in %who, as they can have very large reprs.
1249 # in %who, as they can have very large reprs.
1250 ns['In'] = self.history_manager.input_hist_parsed
1250 ns['In'] = self.history_manager.input_hist_parsed
1251 ns['Out'] = self.history_manager.output_hist
1251 ns['Out'] = self.history_manager.output_hist
1252
1252
1253 # Store myself as the public api!!!
1253 # Store myself as the public api!!!
1254 ns['get_ipython'] = self.get_ipython
1254 ns['get_ipython'] = self.get_ipython
1255
1255
1256 ns['exit'] = self.exiter
1256 ns['exit'] = self.exiter
1257 ns['quit'] = self.exiter
1257 ns['quit'] = self.exiter
1258
1258
1259 # Sync what we've added so far to user_ns_hidden so these aren't seen
1259 # Sync what we've added so far to user_ns_hidden so these aren't seen
1260 # by %who
1260 # by %who
1261 self.user_ns_hidden.update(ns)
1261 self.user_ns_hidden.update(ns)
1262
1262
1263 # Anything put into ns now would show up in %who. Think twice before
1263 # Anything put into ns now would show up in %who. Think twice before
1264 # putting anything here, as we really want %who to show the user their
1264 # putting anything here, as we really want %who to show the user their
1265 # stuff, not our variables.
1265 # stuff, not our variables.
1266
1266
1267 # Finally, update the real user's namespace
1267 # Finally, update the real user's namespace
1268 self.user_ns.update(ns)
1268 self.user_ns.update(ns)
1269
1269
1270 @property
1270 @property
1271 def all_ns_refs(self):
1271 def all_ns_refs(self):
1272 """Get a list of references to all the namespace dictionaries in which
1272 """Get a list of references to all the namespace dictionaries in which
1273 IPython might store a user-created object.
1273 IPython might store a user-created object.
1274
1274
1275 Note that this does not include the displayhook, which also caches
1275 Note that this does not include the displayhook, which also caches
1276 objects from the output."""
1276 objects from the output."""
1277 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1277 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1278 [m.__dict__ for m in self._main_mod_cache.values()]
1278 [m.__dict__ for m in self._main_mod_cache.values()]
1279
1279
1280 def reset(self, new_session=True, aggressive=False):
1280 def reset(self, new_session=True, aggressive=False):
1281 """Clear all internal namespaces, and attempt to release references to
1281 """Clear all internal namespaces, and attempt to release references to
1282 user objects.
1282 user objects.
1283
1283
1284 If new_session is True, a new history session will be opened.
1284 If new_session is True, a new history session will be opened.
1285 """
1285 """
1286 # Clear histories
1286 # Clear histories
1287 self.history_manager.reset(new_session)
1287 self.history_manager.reset(new_session)
1288 # Reset counter used to index all histories
1288 # Reset counter used to index all histories
1289 if new_session:
1289 if new_session:
1290 self.execution_count = 1
1290 self.execution_count = 1
1291
1291
1292 # Reset last execution result
1292 # Reset last execution result
1293 self.last_execution_succeeded = True
1293 self.last_execution_succeeded = True
1294 self.last_execution_result = None
1294 self.last_execution_result = None
1295
1295
1296 # Flush cached output items
1296 # Flush cached output items
1297 if self.displayhook.do_full_cache:
1297 if self.displayhook.do_full_cache:
1298 self.displayhook.flush()
1298 self.displayhook.flush()
1299
1299
1300 # The main execution namespaces must be cleared very carefully,
1300 # The main execution namespaces must be cleared very carefully,
1301 # skipping the deletion of the builtin-related keys, because doing so
1301 # skipping the deletion of the builtin-related keys, because doing so
1302 # would cause errors in many object's __del__ methods.
1302 # would cause errors in many object's __del__ methods.
1303 if self.user_ns is not self.user_global_ns:
1303 if self.user_ns is not self.user_global_ns:
1304 self.user_ns.clear()
1304 self.user_ns.clear()
1305 ns = self.user_global_ns
1305 ns = self.user_global_ns
1306 drop_keys = set(ns.keys())
1306 drop_keys = set(ns.keys())
1307 drop_keys.discard('__builtin__')
1307 drop_keys.discard('__builtin__')
1308 drop_keys.discard('__builtins__')
1308 drop_keys.discard('__builtins__')
1309 drop_keys.discard('__name__')
1309 drop_keys.discard('__name__')
1310 for k in drop_keys:
1310 for k in drop_keys:
1311 del ns[k]
1311 del ns[k]
1312
1312
1313 self.user_ns_hidden.clear()
1313 self.user_ns_hidden.clear()
1314
1314
1315 # Restore the user namespaces to minimal usability
1315 # Restore the user namespaces to minimal usability
1316 self.init_user_ns()
1316 self.init_user_ns()
1317 if aggressive and not hasattr(self, "_sys_modules_keys"):
1317 if aggressive and not hasattr(self, "_sys_modules_keys"):
1318 print("Cannot restore sys.module, no snapshot")
1318 print("Cannot restore sys.module, no snapshot")
1319 elif aggressive:
1319 elif aggressive:
1320 print("culling sys module...")
1320 print("culling sys module...")
1321 current_keys = set(sys.modules.keys())
1321 current_keys = set(sys.modules.keys())
1322 for k in current_keys - self._sys_modules_keys:
1322 for k in current_keys - self._sys_modules_keys:
1323 if k.startswith("multiprocessing"):
1323 if k.startswith("multiprocessing"):
1324 continue
1324 continue
1325 del sys.modules[k]
1325 del sys.modules[k]
1326
1326
1327 # Restore the default and user aliases
1327 # Restore the default and user aliases
1328 self.alias_manager.clear_aliases()
1328 self.alias_manager.clear_aliases()
1329 self.alias_manager.init_aliases()
1329 self.alias_manager.init_aliases()
1330
1330
1331 # Now define aliases that only make sense on the terminal, because they
1331 # Now define aliases that only make sense on the terminal, because they
1332 # need direct access to the console in a way that we can't emulate in
1332 # need direct access to the console in a way that we can't emulate in
1333 # GUI or web frontend
1333 # GUI or web frontend
1334 if os.name == 'posix':
1334 if os.name == 'posix':
1335 for cmd in ('clear', 'more', 'less', 'man'):
1335 for cmd in ('clear', 'more', 'less', 'man'):
1336 if cmd not in self.magics_manager.magics['line']:
1336 if cmd not in self.magics_manager.magics['line']:
1337 self.alias_manager.soft_define_alias(cmd, cmd)
1337 self.alias_manager.soft_define_alias(cmd, cmd)
1338
1338
1339 # Flush the private list of module references kept for script
1339 # Flush the private list of module references kept for script
1340 # execution protection
1340 # execution protection
1341 self.clear_main_mod_cache()
1341 self.clear_main_mod_cache()
1342
1342
1343 def del_var(self, varname, by_name=False):
1343 def del_var(self, varname, by_name=False):
1344 """Delete a variable from the various namespaces, so that, as
1344 """Delete a variable from the various namespaces, so that, as
1345 far as possible, we're not keeping any hidden references to it.
1345 far as possible, we're not keeping any hidden references to it.
1346
1346
1347 Parameters
1347 Parameters
1348 ----------
1348 ----------
1349 varname : str
1349 varname : str
1350 The name of the variable to delete.
1350 The name of the variable to delete.
1351 by_name : bool
1351 by_name : bool
1352 If True, delete variables with the given name in each
1352 If True, delete variables with the given name in each
1353 namespace. If False (default), find the variable in the user
1353 namespace. If False (default), find the variable in the user
1354 namespace, and delete references to it.
1354 namespace, and delete references to it.
1355 """
1355 """
1356 if varname in ('__builtin__', '__builtins__'):
1356 if varname in ('__builtin__', '__builtins__'):
1357 raise ValueError("Refusing to delete %s" % varname)
1357 raise ValueError("Refusing to delete %s" % varname)
1358
1358
1359 ns_refs = self.all_ns_refs
1359 ns_refs = self.all_ns_refs
1360
1360
1361 if by_name: # Delete by name
1361 if by_name: # Delete by name
1362 for ns in ns_refs:
1362 for ns in ns_refs:
1363 try:
1363 try:
1364 del ns[varname]
1364 del ns[varname]
1365 except KeyError:
1365 except KeyError:
1366 pass
1366 pass
1367 else: # Delete by object
1367 else: # Delete by object
1368 try:
1368 try:
1369 obj = self.user_ns[varname]
1369 obj = self.user_ns[varname]
1370 except KeyError as e:
1370 except KeyError as e:
1371 raise NameError("name '%s' is not defined" % varname) from e
1371 raise NameError("name '%s' is not defined" % varname) from e
1372 # Also check in output history
1372 # Also check in output history
1373 ns_refs.append(self.history_manager.output_hist)
1373 ns_refs.append(self.history_manager.output_hist)
1374 for ns in ns_refs:
1374 for ns in ns_refs:
1375 to_delete = [n for n, o in ns.items() if o is obj]
1375 to_delete = [n for n, o in ns.items() if o is obj]
1376 for name in to_delete:
1376 for name in to_delete:
1377 del ns[name]
1377 del ns[name]
1378
1378
1379 # Ensure it is removed from the last execution result
1379 # Ensure it is removed from the last execution result
1380 if self.last_execution_result.result is obj:
1380 if self.last_execution_result.result is obj:
1381 self.last_execution_result = None
1381 self.last_execution_result = None
1382
1382
1383 # displayhook keeps extra references, but not in a dictionary
1383 # displayhook keeps extra references, but not in a dictionary
1384 for name in ('_', '__', '___'):
1384 for name in ('_', '__', '___'):
1385 if getattr(self.displayhook, name) is obj:
1385 if getattr(self.displayhook, name) is obj:
1386 setattr(self.displayhook, name, None)
1386 setattr(self.displayhook, name, None)
1387
1387
1388 def reset_selective(self, regex=None):
1388 def reset_selective(self, regex=None):
1389 """Clear selective variables from internal namespaces based on a
1389 """Clear selective variables from internal namespaces based on a
1390 specified regular expression.
1390 specified regular expression.
1391
1391
1392 Parameters
1392 Parameters
1393 ----------
1393 ----------
1394 regex : string or compiled pattern, optional
1394 regex : string or compiled pattern, optional
1395 A regular expression pattern that will be used in searching
1395 A regular expression pattern that will be used in searching
1396 variable names in the users namespaces.
1396 variable names in the users namespaces.
1397 """
1397 """
1398 if regex is not None:
1398 if regex is not None:
1399 try:
1399 try:
1400 m = re.compile(regex)
1400 m = re.compile(regex)
1401 except TypeError as e:
1401 except TypeError as e:
1402 raise TypeError('regex must be a string or compiled pattern') from e
1402 raise TypeError('regex must be a string or compiled pattern') from e
1403 # Search for keys in each namespace that match the given regex
1403 # Search for keys in each namespace that match the given regex
1404 # If a match is found, delete the key/value pair.
1404 # If a match is found, delete the key/value pair.
1405 for ns in self.all_ns_refs:
1405 for ns in self.all_ns_refs:
1406 for var in ns:
1406 for var in ns:
1407 if m.search(var):
1407 if m.search(var):
1408 del ns[var]
1408 del ns[var]
1409
1409
1410 def push(self, variables, interactive=True):
1410 def push(self, variables, interactive=True):
1411 """Inject a group of variables into the IPython user namespace.
1411 """Inject a group of variables into the IPython user namespace.
1412
1412
1413 Parameters
1413 Parameters
1414 ----------
1414 ----------
1415 variables : dict, str or list/tuple of str
1415 variables : dict, str or list/tuple of str
1416 The variables to inject into the user's namespace. If a dict, a
1416 The variables to inject into the user's namespace. If a dict, a
1417 simple update is done. If a str, the string is assumed to have
1417 simple update is done. If a str, the string is assumed to have
1418 variable names separated by spaces. A list/tuple of str can also
1418 variable names separated by spaces. A list/tuple of str can also
1419 be used to give the variable names. If just the variable names are
1419 be used to give the variable names. If just the variable names are
1420 give (list/tuple/str) then the variable values looked up in the
1420 give (list/tuple/str) then the variable values looked up in the
1421 callers frame.
1421 callers frame.
1422 interactive : bool
1422 interactive : bool
1423 If True (default), the variables will be listed with the ``who``
1423 If True (default), the variables will be listed with the ``who``
1424 magic.
1424 magic.
1425 """
1425 """
1426 vdict = None
1426 vdict = None
1427
1427
1428 # We need a dict of name/value pairs to do namespace updates.
1428 # We need a dict of name/value pairs to do namespace updates.
1429 if isinstance(variables, dict):
1429 if isinstance(variables, dict):
1430 vdict = variables
1430 vdict = variables
1431 elif isinstance(variables, (str, list, tuple)):
1431 elif isinstance(variables, (str, list, tuple)):
1432 if isinstance(variables, str):
1432 if isinstance(variables, str):
1433 vlist = variables.split()
1433 vlist = variables.split()
1434 else:
1434 else:
1435 vlist = variables
1435 vlist = variables
1436 vdict = {}
1436 vdict = {}
1437 cf = sys._getframe(1)
1437 cf = sys._getframe(1)
1438 for name in vlist:
1438 for name in vlist:
1439 try:
1439 try:
1440 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1440 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1441 except:
1441 except:
1442 print('Could not get variable %s from %s' %
1442 print('Could not get variable %s from %s' %
1443 (name,cf.f_code.co_name))
1443 (name,cf.f_code.co_name))
1444 else:
1444 else:
1445 raise ValueError('variables must be a dict/str/list/tuple')
1445 raise ValueError('variables must be a dict/str/list/tuple')
1446
1446
1447 # Propagate variables to user namespace
1447 # Propagate variables to user namespace
1448 self.user_ns.update(vdict)
1448 self.user_ns.update(vdict)
1449
1449
1450 # And configure interactive visibility
1450 # And configure interactive visibility
1451 user_ns_hidden = self.user_ns_hidden
1451 user_ns_hidden = self.user_ns_hidden
1452 if interactive:
1452 if interactive:
1453 for name in vdict:
1453 for name in vdict:
1454 user_ns_hidden.pop(name, None)
1454 user_ns_hidden.pop(name, None)
1455 else:
1455 else:
1456 user_ns_hidden.update(vdict)
1456 user_ns_hidden.update(vdict)
1457
1457
1458 def drop_by_id(self, variables):
1458 def drop_by_id(self, variables):
1459 """Remove a dict of variables from the user namespace, if they are the
1459 """Remove a dict of variables from the user namespace, if they are the
1460 same as the values in the dictionary.
1460 same as the values in the dictionary.
1461
1461
1462 This is intended for use by extensions: variables that they've added can
1462 This is intended for use by extensions: variables that they've added can
1463 be taken back out if they are unloaded, without removing any that the
1463 be taken back out if they are unloaded, without removing any that the
1464 user has overwritten.
1464 user has overwritten.
1465
1465
1466 Parameters
1466 Parameters
1467 ----------
1467 ----------
1468 variables : dict
1468 variables : dict
1469 A dictionary mapping object names (as strings) to the objects.
1469 A dictionary mapping object names (as strings) to the objects.
1470 """
1470 """
1471 for name, obj in variables.items():
1471 for name, obj in variables.items():
1472 if name in self.user_ns and self.user_ns[name] is obj:
1472 if name in self.user_ns and self.user_ns[name] is obj:
1473 del self.user_ns[name]
1473 del self.user_ns[name]
1474 self.user_ns_hidden.pop(name, None)
1474 self.user_ns_hidden.pop(name, None)
1475
1475
1476 #-------------------------------------------------------------------------
1476 #-------------------------------------------------------------------------
1477 # Things related to object introspection
1477 # Things related to object introspection
1478 #-------------------------------------------------------------------------
1478 #-------------------------------------------------------------------------
1479
1479
1480 def _ofind(self, oname, namespaces=None):
1480 def _ofind(self, oname, namespaces=None):
1481 """Find an object in the available namespaces.
1481 """Find an object in the available namespaces.
1482
1482
1483 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1483 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1484
1484
1485 Has special code to detect magic functions.
1485 Has special code to detect magic functions.
1486 """
1486 """
1487 oname = oname.strip()
1487 oname = oname.strip()
1488 if not oname.startswith(ESC_MAGIC) and \
1488 if not oname.startswith(ESC_MAGIC) and \
1489 not oname.startswith(ESC_MAGIC2) and \
1489 not oname.startswith(ESC_MAGIC2) and \
1490 not all(a.isidentifier() for a in oname.split(".")):
1490 not all(a.isidentifier() for a in oname.split(".")):
1491 return {'found': False}
1491 return {'found': False}
1492
1492
1493 if namespaces is None:
1493 if namespaces is None:
1494 # Namespaces to search in:
1494 # Namespaces to search in:
1495 # Put them in a list. The order is important so that we
1495 # Put them in a list. The order is important so that we
1496 # find things in the same order that Python finds them.
1496 # find things in the same order that Python finds them.
1497 namespaces = [ ('Interactive', self.user_ns),
1497 namespaces = [ ('Interactive', self.user_ns),
1498 ('Interactive (global)', self.user_global_ns),
1498 ('Interactive (global)', self.user_global_ns),
1499 ('Python builtin', builtin_mod.__dict__),
1499 ('Python builtin', builtin_mod.__dict__),
1500 ]
1500 ]
1501
1501
1502 ismagic = False
1502 ismagic = False
1503 isalias = False
1503 isalias = False
1504 found = False
1504 found = False
1505 ospace = None
1505 ospace = None
1506 parent = None
1506 parent = None
1507 obj = None
1507 obj = None
1508
1508
1509
1509
1510 # Look for the given name by splitting it in parts. If the head is
1510 # Look for the given name by splitting it in parts. If the head is
1511 # found, then we look for all the remaining parts as members, and only
1511 # found, then we look for all the remaining parts as members, and only
1512 # declare success if we can find them all.
1512 # declare success if we can find them all.
1513 oname_parts = oname.split('.')
1513 oname_parts = oname.split('.')
1514 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1514 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1515 for nsname,ns in namespaces:
1515 for nsname,ns in namespaces:
1516 try:
1516 try:
1517 obj = ns[oname_head]
1517 obj = ns[oname_head]
1518 except KeyError:
1518 except KeyError:
1519 continue
1519 continue
1520 else:
1520 else:
1521 for idx, part in enumerate(oname_rest):
1521 for idx, part in enumerate(oname_rest):
1522 try:
1522 try:
1523 parent = obj
1523 parent = obj
1524 # The last part is looked up in a special way to avoid
1524 # The last part is looked up in a special way to avoid
1525 # descriptor invocation as it may raise or have side
1525 # descriptor invocation as it may raise or have side
1526 # effects.
1526 # effects.
1527 if idx == len(oname_rest) - 1:
1527 if idx == len(oname_rest) - 1:
1528 obj = self._getattr_property(obj, part)
1528 obj = self._getattr_property(obj, part)
1529 else:
1529 else:
1530 obj = getattr(obj, part)
1530 obj = getattr(obj, part)
1531 except:
1531 except:
1532 # Blanket except b/c some badly implemented objects
1532 # Blanket except b/c some badly implemented objects
1533 # allow __getattr__ to raise exceptions other than
1533 # allow __getattr__ to raise exceptions other than
1534 # AttributeError, which then crashes IPython.
1534 # AttributeError, which then crashes IPython.
1535 break
1535 break
1536 else:
1536 else:
1537 # If we finish the for loop (no break), we got all members
1537 # If we finish the for loop (no break), we got all members
1538 found = True
1538 found = True
1539 ospace = nsname
1539 ospace = nsname
1540 break # namespace loop
1540 break # namespace loop
1541
1541
1542 # Try to see if it's magic
1542 # Try to see if it's magic
1543 if not found:
1543 if not found:
1544 obj = None
1544 obj = None
1545 if oname.startswith(ESC_MAGIC2):
1545 if oname.startswith(ESC_MAGIC2):
1546 oname = oname.lstrip(ESC_MAGIC2)
1546 oname = oname.lstrip(ESC_MAGIC2)
1547 obj = self.find_cell_magic(oname)
1547 obj = self.find_cell_magic(oname)
1548 elif oname.startswith(ESC_MAGIC):
1548 elif oname.startswith(ESC_MAGIC):
1549 oname = oname.lstrip(ESC_MAGIC)
1549 oname = oname.lstrip(ESC_MAGIC)
1550 obj = self.find_line_magic(oname)
1550 obj = self.find_line_magic(oname)
1551 else:
1551 else:
1552 # search without prefix, so run? will find %run?
1552 # search without prefix, so run? will find %run?
1553 obj = self.find_line_magic(oname)
1553 obj = self.find_line_magic(oname)
1554 if obj is None:
1554 if obj is None:
1555 obj = self.find_cell_magic(oname)
1555 obj = self.find_cell_magic(oname)
1556 if obj is not None:
1556 if obj is not None:
1557 found = True
1557 found = True
1558 ospace = 'IPython internal'
1558 ospace = 'IPython internal'
1559 ismagic = True
1559 ismagic = True
1560 isalias = isinstance(obj, Alias)
1560 isalias = isinstance(obj, Alias)
1561
1561
1562 # Last try: special-case some literals like '', [], {}, etc:
1562 # Last try: special-case some literals like '', [], {}, etc:
1563 if not found and oname_head in ["''",'""','[]','{}','()']:
1563 if not found and oname_head in ["''",'""','[]','{}','()']:
1564 obj = eval(oname_head)
1564 obj = eval(oname_head)
1565 found = True
1565 found = True
1566 ospace = 'Interactive'
1566 ospace = 'Interactive'
1567
1567
1568 return {
1568 return {
1569 'obj':obj,
1569 'obj':obj,
1570 'found':found,
1570 'found':found,
1571 'parent':parent,
1571 'parent':parent,
1572 'ismagic':ismagic,
1572 'ismagic':ismagic,
1573 'isalias':isalias,
1573 'isalias':isalias,
1574 'namespace':ospace
1574 'namespace':ospace
1575 }
1575 }
1576
1576
1577 @staticmethod
1577 @staticmethod
1578 def _getattr_property(obj, attrname):
1578 def _getattr_property(obj, attrname):
1579 """Property-aware getattr to use in object finding.
1579 """Property-aware getattr to use in object finding.
1580
1580
1581 If attrname represents a property, return it unevaluated (in case it has
1581 If attrname represents a property, return it unevaluated (in case it has
1582 side effects or raises an error.
1582 side effects or raises an error.
1583
1583
1584 """
1584 """
1585 if not isinstance(obj, type):
1585 if not isinstance(obj, type):
1586 try:
1586 try:
1587 # `getattr(type(obj), attrname)` is not guaranteed to return
1587 # `getattr(type(obj), attrname)` is not guaranteed to return
1588 # `obj`, but does so for property:
1588 # `obj`, but does so for property:
1589 #
1589 #
1590 # property.__get__(self, None, cls) -> self
1590 # property.__get__(self, None, cls) -> self
1591 #
1591 #
1592 # The universal alternative is to traverse the mro manually
1592 # The universal alternative is to traverse the mro manually
1593 # searching for attrname in class dicts.
1593 # searching for attrname in class dicts.
1594 attr = getattr(type(obj), attrname)
1594 attr = getattr(type(obj), attrname)
1595 except AttributeError:
1595 except AttributeError:
1596 pass
1596 pass
1597 else:
1597 else:
1598 # This relies on the fact that data descriptors (with both
1598 # This relies on the fact that data descriptors (with both
1599 # __get__ & __set__ magic methods) take precedence over
1599 # __get__ & __set__ magic methods) take precedence over
1600 # instance-level attributes:
1600 # instance-level attributes:
1601 #
1601 #
1602 # class A(object):
1602 # class A(object):
1603 # @property
1603 # @property
1604 # def foobar(self): return 123
1604 # def foobar(self): return 123
1605 # a = A()
1605 # a = A()
1606 # a.__dict__['foobar'] = 345
1606 # a.__dict__['foobar'] = 345
1607 # a.foobar # == 123
1607 # a.foobar # == 123
1608 #
1608 #
1609 # So, a property may be returned right away.
1609 # So, a property may be returned right away.
1610 if isinstance(attr, property):
1610 if isinstance(attr, property):
1611 return attr
1611 return attr
1612
1612
1613 # Nothing helped, fall back.
1613 # Nothing helped, fall back.
1614 return getattr(obj, attrname)
1614 return getattr(obj, attrname)
1615
1615
1616 def _object_find(self, oname, namespaces=None):
1616 def _object_find(self, oname, namespaces=None):
1617 """Find an object and return a struct with info about it."""
1617 """Find an object and return a struct with info about it."""
1618 return Struct(self._ofind(oname, namespaces))
1618 return Struct(self._ofind(oname, namespaces))
1619
1619
1620 def _inspect(self, meth, oname, namespaces=None, **kw):
1620 def _inspect(self, meth, oname, namespaces=None, **kw):
1621 """Generic interface to the inspector system.
1621 """Generic interface to the inspector system.
1622
1622
1623 This function is meant to be called by pdef, pdoc & friends.
1623 This function is meant to be called by pdef, pdoc & friends.
1624 """
1624 """
1625 info = self._object_find(oname, namespaces)
1625 info = self._object_find(oname, namespaces)
1626 docformat = sphinxify if self.sphinxify_docstring else None
1626 docformat = sphinxify if self.sphinxify_docstring else None
1627 if info.found:
1627 if info.found:
1628 pmethod = getattr(self.inspector, meth)
1628 pmethod = getattr(self.inspector, meth)
1629 # TODO: only apply format_screen to the plain/text repr of the mime
1629 # TODO: only apply format_screen to the plain/text repr of the mime
1630 # bundle.
1630 # bundle.
1631 formatter = format_screen if info.ismagic else docformat
1631 formatter = format_screen if info.ismagic else docformat
1632 if meth == 'pdoc':
1632 if meth == 'pdoc':
1633 pmethod(info.obj, oname, formatter)
1633 pmethod(info.obj, oname, formatter)
1634 elif meth == 'pinfo':
1634 elif meth == 'pinfo':
1635 pmethod(
1635 pmethod(
1636 info.obj,
1636 info.obj,
1637 oname,
1637 oname,
1638 formatter,
1638 formatter,
1639 info,
1639 info,
1640 enable_html_pager=self.enable_html_pager,
1640 enable_html_pager=self.enable_html_pager,
1641 **kw
1641 **kw
1642 )
1642 )
1643 else:
1643 else:
1644 pmethod(info.obj, oname)
1644 pmethod(info.obj, oname)
1645 else:
1645 else:
1646 print('Object `%s` not found.' % oname)
1646 print('Object `%s` not found.' % oname)
1647 return 'not found' # so callers can take other action
1647 return 'not found' # so callers can take other action
1648
1648
1649 def object_inspect(self, oname, detail_level=0):
1649 def object_inspect(self, oname, detail_level=0):
1650 """Get object info about oname"""
1650 """Get object info about oname"""
1651 with self.builtin_trap:
1651 with self.builtin_trap:
1652 info = self._object_find(oname)
1652 info = self._object_find(oname)
1653 if info.found:
1653 if info.found:
1654 return self.inspector.info(info.obj, oname, info=info,
1654 return self.inspector.info(info.obj, oname, info=info,
1655 detail_level=detail_level
1655 detail_level=detail_level
1656 )
1656 )
1657 else:
1657 else:
1658 return oinspect.object_info(name=oname, found=False)
1658 return oinspect.object_info(name=oname, found=False)
1659
1659
1660 def object_inspect_text(self, oname, detail_level=0):
1660 def object_inspect_text(self, oname, detail_level=0):
1661 """Get object info as formatted text"""
1661 """Get object info as formatted text"""
1662 return self.object_inspect_mime(oname, detail_level)['text/plain']
1662 return self.object_inspect_mime(oname, detail_level)['text/plain']
1663
1663
1664 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1664 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1665 """Get object info as a mimebundle of formatted representations.
1665 """Get object info as a mimebundle of formatted representations.
1666
1666
1667 A mimebundle is a dictionary, keyed by mime-type.
1667 A mimebundle is a dictionary, keyed by mime-type.
1668 It must always have the key `'text/plain'`.
1668 It must always have the key `'text/plain'`.
1669 """
1669 """
1670 with self.builtin_trap:
1670 with self.builtin_trap:
1671 info = self._object_find(oname)
1671 info = self._object_find(oname)
1672 if info.found:
1672 if info.found:
1673 docformat = sphinxify if self.sphinxify_docstring else None
1673 docformat = sphinxify if self.sphinxify_docstring else None
1674 return self.inspector._get_info(
1674 return self.inspector._get_info(
1675 info.obj,
1675 info.obj,
1676 oname,
1676 oname,
1677 info=info,
1677 info=info,
1678 detail_level=detail_level,
1678 detail_level=detail_level,
1679 formatter=docformat,
1679 formatter=docformat,
1680 omit_sections=omit_sections,
1680 omit_sections=omit_sections,
1681 )
1681 )
1682 else:
1682 else:
1683 raise KeyError(oname)
1683 raise KeyError(oname)
1684
1684
1685 #-------------------------------------------------------------------------
1685 #-------------------------------------------------------------------------
1686 # Things related to history management
1686 # Things related to history management
1687 #-------------------------------------------------------------------------
1687 #-------------------------------------------------------------------------
1688
1688
1689 def init_history(self):
1689 def init_history(self):
1690 """Sets up the command history, and starts regular autosaves."""
1690 """Sets up the command history, and starts regular autosaves."""
1691 self.history_manager = HistoryManager(shell=self, parent=self)
1691 self.history_manager = HistoryManager(shell=self, parent=self)
1692 self.configurables.append(self.history_manager)
1692 self.configurables.append(self.history_manager)
1693
1693
1694 #-------------------------------------------------------------------------
1694 #-------------------------------------------------------------------------
1695 # Things related to exception handling and tracebacks (not debugging)
1695 # Things related to exception handling and tracebacks (not debugging)
1696 #-------------------------------------------------------------------------
1696 #-------------------------------------------------------------------------
1697
1697
1698 debugger_cls = InterruptiblePdb
1698 debugger_cls = InterruptiblePdb
1699
1699
1700 def init_traceback_handlers(self, custom_exceptions):
1700 def init_traceback_handlers(self, custom_exceptions):
1701 # Syntax error handler.
1701 # Syntax error handler.
1702 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1702 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1703
1703
1704 # The interactive one is initialized with an offset, meaning we always
1704 # The interactive one is initialized with an offset, meaning we always
1705 # want to remove the topmost item in the traceback, which is our own
1705 # want to remove the topmost item in the traceback, which is our own
1706 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1706 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1707 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1707 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1708 color_scheme='NoColor',
1708 color_scheme='NoColor',
1709 tb_offset = 1,
1709 tb_offset = 1,
1710 check_cache=check_linecache_ipython,
1710 check_cache=check_linecache_ipython,
1711 debugger_cls=self.debugger_cls, parent=self)
1711 debugger_cls=self.debugger_cls, parent=self)
1712
1712
1713 # The instance will store a pointer to the system-wide exception hook,
1713 # The instance will store a pointer to the system-wide exception hook,
1714 # so that runtime code (such as magics) can access it. This is because
1714 # so that runtime code (such as magics) can access it. This is because
1715 # during the read-eval loop, it may get temporarily overwritten.
1715 # during the read-eval loop, it may get temporarily overwritten.
1716 self.sys_excepthook = sys.excepthook
1716 self.sys_excepthook = sys.excepthook
1717
1717
1718 # and add any custom exception handlers the user may have specified
1718 # and add any custom exception handlers the user may have specified
1719 self.set_custom_exc(*custom_exceptions)
1719 self.set_custom_exc(*custom_exceptions)
1720
1720
1721 # Set the exception mode
1721 # Set the exception mode
1722 self.InteractiveTB.set_mode(mode=self.xmode)
1722 self.InteractiveTB.set_mode(mode=self.xmode)
1723
1723
1724 def set_custom_exc(self, exc_tuple, handler):
1724 def set_custom_exc(self, exc_tuple, handler):
1725 """set_custom_exc(exc_tuple, handler)
1725 """set_custom_exc(exc_tuple, handler)
1726
1726
1727 Set a custom exception handler, which will be called if any of the
1727 Set a custom exception handler, which will be called if any of the
1728 exceptions in exc_tuple occur in the mainloop (specifically, in the
1728 exceptions in exc_tuple occur in the mainloop (specifically, in the
1729 run_code() method).
1729 run_code() method).
1730
1730
1731 Parameters
1731 Parameters
1732 ----------
1732 ----------
1733
1733
1734 exc_tuple : tuple of exception classes
1734 exc_tuple : tuple of exception classes
1735 A *tuple* of exception classes, for which to call the defined
1735 A *tuple* of exception classes, for which to call the defined
1736 handler. It is very important that you use a tuple, and NOT A
1736 handler. It is very important that you use a tuple, and NOT A
1737 LIST here, because of the way Python's except statement works. If
1737 LIST here, because of the way Python's except statement works. If
1738 you only want to trap a single exception, use a singleton tuple::
1738 you only want to trap a single exception, use a singleton tuple::
1739
1739
1740 exc_tuple == (MyCustomException,)
1740 exc_tuple == (MyCustomException,)
1741
1741
1742 handler : callable
1742 handler : callable
1743 handler must have the following signature::
1743 handler must have the following signature::
1744
1744
1745 def my_handler(self, etype, value, tb, tb_offset=None):
1745 def my_handler(self, etype, value, tb, tb_offset=None):
1746 ...
1746 ...
1747 return structured_traceback
1747 return structured_traceback
1748
1748
1749 Your handler must return a structured traceback (a list of strings),
1749 Your handler must return a structured traceback (a list of strings),
1750 or None.
1750 or None.
1751
1751
1752 This will be made into an instance method (via types.MethodType)
1752 This will be made into an instance method (via types.MethodType)
1753 of IPython itself, and it will be called if any of the exceptions
1753 of IPython itself, and it will be called if any of the exceptions
1754 listed in the exc_tuple are caught. If the handler is None, an
1754 listed in the exc_tuple are caught. If the handler is None, an
1755 internal basic one is used, which just prints basic info.
1755 internal basic one is used, which just prints basic info.
1756
1756
1757 To protect IPython from crashes, if your handler ever raises an
1757 To protect IPython from crashes, if your handler ever raises an
1758 exception or returns an invalid result, it will be immediately
1758 exception or returns an invalid result, it will be immediately
1759 disabled.
1759 disabled.
1760
1760
1761 Notes
1761 Notes
1762 -----
1762 -----
1763
1763
1764 WARNING: by putting in your own exception handler into IPython's main
1764 WARNING: by putting in your own exception handler into IPython's main
1765 execution loop, you run a very good chance of nasty crashes. This
1765 execution loop, you run a very good chance of nasty crashes. This
1766 facility should only be used if you really know what you are doing.
1766 facility should only be used if you really know what you are doing.
1767 """
1767 """
1768
1768
1769 if not isinstance(exc_tuple, tuple):
1769 if not isinstance(exc_tuple, tuple):
1770 raise TypeError("The custom exceptions must be given as a tuple.")
1770 raise TypeError("The custom exceptions must be given as a tuple.")
1771
1771
1772 def dummy_handler(self, etype, value, tb, tb_offset=None):
1772 def dummy_handler(self, etype, value, tb, tb_offset=None):
1773 print('*** Simple custom exception handler ***')
1773 print('*** Simple custom exception handler ***')
1774 print('Exception type :', etype)
1774 print('Exception type :', etype)
1775 print('Exception value:', value)
1775 print('Exception value:', value)
1776 print('Traceback :', tb)
1776 print('Traceback :', tb)
1777
1777
1778 def validate_stb(stb):
1778 def validate_stb(stb):
1779 """validate structured traceback return type
1779 """validate structured traceback return type
1780
1780
1781 return type of CustomTB *should* be a list of strings, but allow
1781 return type of CustomTB *should* be a list of strings, but allow
1782 single strings or None, which are harmless.
1782 single strings or None, which are harmless.
1783
1783
1784 This function will *always* return a list of strings,
1784 This function will *always* return a list of strings,
1785 and will raise a TypeError if stb is inappropriate.
1785 and will raise a TypeError if stb is inappropriate.
1786 """
1786 """
1787 msg = "CustomTB must return list of strings, not %r" % stb
1787 msg = "CustomTB must return list of strings, not %r" % stb
1788 if stb is None:
1788 if stb is None:
1789 return []
1789 return []
1790 elif isinstance(stb, str):
1790 elif isinstance(stb, str):
1791 return [stb]
1791 return [stb]
1792 elif not isinstance(stb, list):
1792 elif not isinstance(stb, list):
1793 raise TypeError(msg)
1793 raise TypeError(msg)
1794 # it's a list
1794 # it's a list
1795 for line in stb:
1795 for line in stb:
1796 # check every element
1796 # check every element
1797 if not isinstance(line, str):
1797 if not isinstance(line, str):
1798 raise TypeError(msg)
1798 raise TypeError(msg)
1799 return stb
1799 return stb
1800
1800
1801 if handler is None:
1801 if handler is None:
1802 wrapped = dummy_handler
1802 wrapped = dummy_handler
1803 else:
1803 else:
1804 def wrapped(self,etype,value,tb,tb_offset=None):
1804 def wrapped(self,etype,value,tb,tb_offset=None):
1805 """wrap CustomTB handler, to protect IPython from user code
1805 """wrap CustomTB handler, to protect IPython from user code
1806
1806
1807 This makes it harder (but not impossible) for custom exception
1807 This makes it harder (but not impossible) for custom exception
1808 handlers to crash IPython.
1808 handlers to crash IPython.
1809 """
1809 """
1810 try:
1810 try:
1811 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1811 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1812 return validate_stb(stb)
1812 return validate_stb(stb)
1813 except:
1813 except:
1814 # clear custom handler immediately
1814 # clear custom handler immediately
1815 self.set_custom_exc((), None)
1815 self.set_custom_exc((), None)
1816 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1816 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1817 # show the exception in handler first
1817 # show the exception in handler first
1818 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1818 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1819 print(self.InteractiveTB.stb2text(stb))
1819 print(self.InteractiveTB.stb2text(stb))
1820 print("The original exception:")
1820 print("The original exception:")
1821 stb = self.InteractiveTB.structured_traceback(
1821 stb = self.InteractiveTB.structured_traceback(
1822 (etype,value,tb), tb_offset=tb_offset
1822 (etype,value,tb), tb_offset=tb_offset
1823 )
1823 )
1824 return stb
1824 return stb
1825
1825
1826 self.CustomTB = types.MethodType(wrapped,self)
1826 self.CustomTB = types.MethodType(wrapped,self)
1827 self.custom_exceptions = exc_tuple
1827 self.custom_exceptions = exc_tuple
1828
1828
1829 def excepthook(self, etype, value, tb):
1829 def excepthook(self, etype, value, tb):
1830 """One more defense for GUI apps that call sys.excepthook.
1830 """One more defense for GUI apps that call sys.excepthook.
1831
1831
1832 GUI frameworks like wxPython trap exceptions and call
1832 GUI frameworks like wxPython trap exceptions and call
1833 sys.excepthook themselves. I guess this is a feature that
1833 sys.excepthook themselves. I guess this is a feature that
1834 enables them to keep running after exceptions that would
1834 enables them to keep running after exceptions that would
1835 otherwise kill their mainloop. This is a bother for IPython
1835 otherwise kill their mainloop. This is a bother for IPython
1836 which expects to catch all of the program exceptions with a try:
1836 which expects to catch all of the program exceptions with a try:
1837 except: statement.
1837 except: statement.
1838
1838
1839 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1839 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1840 any app directly invokes sys.excepthook, it will look to the user like
1840 any app directly invokes sys.excepthook, it will look to the user like
1841 IPython crashed. In order to work around this, we can disable the
1841 IPython crashed. In order to work around this, we can disable the
1842 CrashHandler and replace it with this excepthook instead, which prints a
1842 CrashHandler and replace it with this excepthook instead, which prints a
1843 regular traceback using our InteractiveTB. In this fashion, apps which
1843 regular traceback using our InteractiveTB. In this fashion, apps which
1844 call sys.excepthook will generate a regular-looking exception from
1844 call sys.excepthook will generate a regular-looking exception from
1845 IPython, and the CrashHandler will only be triggered by real IPython
1845 IPython, and the CrashHandler will only be triggered by real IPython
1846 crashes.
1846 crashes.
1847
1847
1848 This hook should be used sparingly, only in places which are not likely
1848 This hook should be used sparingly, only in places which are not likely
1849 to be true IPython errors.
1849 to be true IPython errors.
1850 """
1850 """
1851 self.showtraceback((etype, value, tb), tb_offset=0)
1851 self.showtraceback((etype, value, tb), tb_offset=0)
1852
1852
1853 def _get_exc_info(self, exc_tuple=None):
1853 def _get_exc_info(self, exc_tuple=None):
1854 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1854 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1855
1855
1856 Ensures sys.last_type,value,traceback hold the exc_info we found,
1856 Ensures sys.last_type,value,traceback hold the exc_info we found,
1857 from whichever source.
1857 from whichever source.
1858
1858
1859 raises ValueError if none of these contain any information
1859 raises ValueError if none of these contain any information
1860 """
1860 """
1861 if exc_tuple is None:
1861 if exc_tuple is None:
1862 etype, value, tb = sys.exc_info()
1862 etype, value, tb = sys.exc_info()
1863 else:
1863 else:
1864 etype, value, tb = exc_tuple
1864 etype, value, tb = exc_tuple
1865
1865
1866 if etype is None:
1866 if etype is None:
1867 if hasattr(sys, 'last_type'):
1867 if hasattr(sys, 'last_type'):
1868 etype, value, tb = sys.last_type, sys.last_value, \
1868 etype, value, tb = sys.last_type, sys.last_value, \
1869 sys.last_traceback
1869 sys.last_traceback
1870
1870
1871 if etype is None:
1871 if etype is None:
1872 raise ValueError("No exception to find")
1872 raise ValueError("No exception to find")
1873
1873
1874 # Now store the exception info in sys.last_type etc.
1874 # Now store the exception info in sys.last_type etc.
1875 # WARNING: these variables are somewhat deprecated and not
1875 # WARNING: these variables are somewhat deprecated and not
1876 # necessarily safe to use in a threaded environment, but tools
1876 # necessarily safe to use in a threaded environment, but tools
1877 # like pdb depend on their existence, so let's set them. If we
1877 # like pdb depend on their existence, so let's set them. If we
1878 # find problems in the field, we'll need to revisit their use.
1878 # find problems in the field, we'll need to revisit their use.
1879 sys.last_type = etype
1879 sys.last_type = etype
1880 sys.last_value = value
1880 sys.last_value = value
1881 sys.last_traceback = tb
1881 sys.last_traceback = tb
1882
1882
1883 return etype, value, tb
1883 return etype, value, tb
1884
1884
1885 def show_usage_error(self, exc):
1885 def show_usage_error(self, exc):
1886 """Show a short message for UsageErrors
1886 """Show a short message for UsageErrors
1887
1887
1888 These are special exceptions that shouldn't show a traceback.
1888 These are special exceptions that shouldn't show a traceback.
1889 """
1889 """
1890 print("UsageError: %s" % exc, file=sys.stderr)
1890 print("UsageError: %s" % exc, file=sys.stderr)
1891
1891
1892 def get_exception_only(self, exc_tuple=None):
1892 def get_exception_only(self, exc_tuple=None):
1893 """
1893 """
1894 Return as a string (ending with a newline) the exception that
1894 Return as a string (ending with a newline) the exception that
1895 just occurred, without any traceback.
1895 just occurred, without any traceback.
1896 """
1896 """
1897 etype, value, tb = self._get_exc_info(exc_tuple)
1897 etype, value, tb = self._get_exc_info(exc_tuple)
1898 msg = traceback.format_exception_only(etype, value)
1898 msg = traceback.format_exception_only(etype, value)
1899 return ''.join(msg)
1899 return ''.join(msg)
1900
1900
1901 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1901 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1902 exception_only=False, running_compiled_code=False):
1902 exception_only=False, running_compiled_code=False):
1903 """Display the exception that just occurred.
1903 """Display the exception that just occurred.
1904
1904
1905 If nothing is known about the exception, this is the method which
1905 If nothing is known about the exception, this is the method which
1906 should be used throughout the code for presenting user tracebacks,
1906 should be used throughout the code for presenting user tracebacks,
1907 rather than directly invoking the InteractiveTB object.
1907 rather than directly invoking the InteractiveTB object.
1908
1908
1909 A specific showsyntaxerror() also exists, but this method can take
1909 A specific showsyntaxerror() also exists, but this method can take
1910 care of calling it if needed, so unless you are explicitly catching a
1910 care of calling it if needed, so unless you are explicitly catching a
1911 SyntaxError exception, don't try to analyze the stack manually and
1911 SyntaxError exception, don't try to analyze the stack manually and
1912 simply call this method."""
1912 simply call this method."""
1913
1913
1914 try:
1914 try:
1915 try:
1915 try:
1916 etype, value, tb = self._get_exc_info(exc_tuple)
1916 etype, value, tb = self._get_exc_info(exc_tuple)
1917 except ValueError:
1917 except ValueError:
1918 print('No traceback available to show.', file=sys.stderr)
1918 print('No traceback available to show.', file=sys.stderr)
1919 return
1919 return
1920
1920
1921 if issubclass(etype, SyntaxError):
1921 if issubclass(etype, SyntaxError):
1922 # Though this won't be called by syntax errors in the input
1922 # Though this won't be called by syntax errors in the input
1923 # line, there may be SyntaxError cases with imported code.
1923 # line, there may be SyntaxError cases with imported code.
1924 self.showsyntaxerror(filename, running_compiled_code)
1924 self.showsyntaxerror(filename, running_compiled_code)
1925 elif etype is UsageError:
1925 elif etype is UsageError:
1926 self.show_usage_error(value)
1926 self.show_usage_error(value)
1927 else:
1927 else:
1928 if exception_only:
1928 if exception_only:
1929 stb = ['An exception has occurred, use %tb to see '
1929 stb = ['An exception has occurred, use %tb to see '
1930 'the full traceback.\n']
1930 'the full traceback.\n']
1931 stb.extend(self.InteractiveTB.get_exception_only(etype,
1931 stb.extend(self.InteractiveTB.get_exception_only(etype,
1932 value))
1932 value))
1933 else:
1933 else:
1934 try:
1934 try:
1935 # Exception classes can customise their traceback - we
1935 # Exception classes can customise their traceback - we
1936 # use this in IPython.parallel for exceptions occurring
1936 # use this in IPython.parallel for exceptions occurring
1937 # in the engines. This should return a list of strings.
1937 # in the engines. This should return a list of strings.
1938 stb = value._render_traceback_()
1938 stb = value._render_traceback_()
1939 except Exception:
1939 except Exception:
1940 stb = self.InteractiveTB.structured_traceback(etype,
1940 stb = self.InteractiveTB.structured_traceback(etype,
1941 value, tb, tb_offset=tb_offset)
1941 value, tb, tb_offset=tb_offset)
1942
1942
1943 self._showtraceback(etype, value, stb)
1943 self._showtraceback(etype, value, stb)
1944 if self.call_pdb:
1944 if self.call_pdb:
1945 # drop into debugger
1945 # drop into debugger
1946 self.debugger(force=True)
1946 self.debugger(force=True)
1947 return
1947 return
1948
1948
1949 # Actually show the traceback
1949 # Actually show the traceback
1950 self._showtraceback(etype, value, stb)
1950 self._showtraceback(etype, value, stb)
1951
1951
1952 except KeyboardInterrupt:
1952 except KeyboardInterrupt:
1953 print('\n' + self.get_exception_only(), file=sys.stderr)
1953 print('\n' + self.get_exception_only(), file=sys.stderr)
1954
1954
1955 def _showtraceback(self, etype, evalue, stb: str):
1955 def _showtraceback(self, etype, evalue, stb: str):
1956 """Actually show a traceback.
1956 """Actually show a traceback.
1957
1957
1958 Subclasses may override this method to put the traceback on a different
1958 Subclasses may override this method to put the traceback on a different
1959 place, like a side channel.
1959 place, like a side channel.
1960 """
1960 """
1961 val = self.InteractiveTB.stb2text(stb)
1961 val = self.InteractiveTB.stb2text(stb)
1962 try:
1962 try:
1963 print(val)
1963 print(val)
1964 except UnicodeEncodeError:
1964 except UnicodeEncodeError:
1965 print(val.encode("utf-8", "backslashreplace").decode())
1965 print(val.encode("utf-8", "backslashreplace").decode())
1966
1966
1967 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1967 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1968 """Display the syntax error that just occurred.
1968 """Display the syntax error that just occurred.
1969
1969
1970 This doesn't display a stack trace because there isn't one.
1970 This doesn't display a stack trace because there isn't one.
1971
1971
1972 If a filename is given, it is stuffed in the exception instead
1972 If a filename is given, it is stuffed in the exception instead
1973 of what was there before (because Python's parser always uses
1973 of what was there before (because Python's parser always uses
1974 "<string>" when reading from a string).
1974 "<string>" when reading from a string).
1975
1975
1976 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1976 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1977 longer stack trace will be displayed.
1977 longer stack trace will be displayed.
1978 """
1978 """
1979 etype, value, last_traceback = self._get_exc_info()
1979 etype, value, last_traceback = self._get_exc_info()
1980
1980
1981 if filename and issubclass(etype, SyntaxError):
1981 if filename and issubclass(etype, SyntaxError):
1982 try:
1982 try:
1983 value.filename = filename
1983 value.filename = filename
1984 except:
1984 except:
1985 # Not the format we expect; leave it alone
1985 # Not the format we expect; leave it alone
1986 pass
1986 pass
1987
1987
1988 # If the error occurred when executing compiled code, we should provide full stacktrace.
1988 # If the error occurred when executing compiled code, we should provide full stacktrace.
1989 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1989 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1990 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1990 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1991 self._showtraceback(etype, value, stb)
1991 self._showtraceback(etype, value, stb)
1992
1992
1993 # This is overridden in TerminalInteractiveShell to show a message about
1993 # This is overridden in TerminalInteractiveShell to show a message about
1994 # the %paste magic.
1994 # the %paste magic.
1995 def showindentationerror(self):
1995 def showindentationerror(self):
1996 """Called by _run_cell when there's an IndentationError in code entered
1996 """Called by _run_cell when there's an IndentationError in code entered
1997 at the prompt.
1997 at the prompt.
1998
1998
1999 This is overridden in TerminalInteractiveShell to show a message about
1999 This is overridden in TerminalInteractiveShell to show a message about
2000 the %paste magic."""
2000 the %paste magic."""
2001 self.showsyntaxerror()
2001 self.showsyntaxerror()
2002
2002
2003 @skip_doctest
2003 @skip_doctest
2004 def set_next_input(self, s, replace=False):
2004 def set_next_input(self, s, replace=False):
2005 """ Sets the 'default' input string for the next command line.
2005 """ Sets the 'default' input string for the next command line.
2006
2006
2007 Example::
2007 Example::
2008
2008
2009 In [1]: _ip.set_next_input("Hello Word")
2009 In [1]: _ip.set_next_input("Hello Word")
2010 In [2]: Hello Word_ # cursor is here
2010 In [2]: Hello Word_ # cursor is here
2011 """
2011 """
2012 self.rl_next_input = s
2012 self.rl_next_input = s
2013
2013
2014 def _indent_current_str(self):
2014 def _indent_current_str(self):
2015 """return the current level of indentation as a string"""
2015 """return the current level of indentation as a string"""
2016 return self.input_splitter.get_indent_spaces() * ' '
2016 return self.input_splitter.get_indent_spaces() * ' '
2017
2017
2018 #-------------------------------------------------------------------------
2018 #-------------------------------------------------------------------------
2019 # Things related to text completion
2019 # Things related to text completion
2020 #-------------------------------------------------------------------------
2020 #-------------------------------------------------------------------------
2021
2021
2022 def init_completer(self):
2022 def init_completer(self):
2023 """Initialize the completion machinery.
2023 """Initialize the completion machinery.
2024
2024
2025 This creates completion machinery that can be used by client code,
2025 This creates completion machinery that can be used by client code,
2026 either interactively in-process (typically triggered by the readline
2026 either interactively in-process (typically triggered by the readline
2027 library), programmatically (such as in test suites) or out-of-process
2027 library), programmatically (such as in test suites) or out-of-process
2028 (typically over the network by remote frontends).
2028 (typically over the network by remote frontends).
2029 """
2029 """
2030 from IPython.core.completer import IPCompleter
2030 from IPython.core.completer import IPCompleter
2031 from IPython.core.completerlib import (module_completer,
2031 from IPython.core.completerlib import (module_completer,
2032 magic_run_completer, cd_completer, reset_completer)
2032 magic_run_completer, cd_completer, reset_completer)
2033
2033
2034 self.Completer = IPCompleter(shell=self,
2034 self.Completer = IPCompleter(shell=self,
2035 namespace=self.user_ns,
2035 namespace=self.user_ns,
2036 global_namespace=self.user_global_ns,
2036 global_namespace=self.user_global_ns,
2037 parent=self,
2037 parent=self,
2038 )
2038 )
2039 self.configurables.append(self.Completer)
2039 self.configurables.append(self.Completer)
2040
2040
2041 # Add custom completers to the basic ones built into IPCompleter
2041 # Add custom completers to the basic ones built into IPCompleter
2042 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2042 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2043 self.strdispatchers['complete_command'] = sdisp
2043 self.strdispatchers['complete_command'] = sdisp
2044 self.Completer.custom_completers = sdisp
2044 self.Completer.custom_completers = sdisp
2045
2045
2046 self.set_hook('complete_command', module_completer, str_key = 'import')
2046 self.set_hook('complete_command', module_completer, str_key = 'import')
2047 self.set_hook('complete_command', module_completer, str_key = 'from')
2047 self.set_hook('complete_command', module_completer, str_key = 'from')
2048 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2048 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2049 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2049 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2050 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2050 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2051 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2051 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2052
2052
2053 @skip_doctest
2053 @skip_doctest
2054 def complete(self, text, line=None, cursor_pos=None):
2054 def complete(self, text, line=None, cursor_pos=None):
2055 """Return the completed text and a list of completions.
2055 """Return the completed text and a list of completions.
2056
2056
2057 Parameters
2057 Parameters
2058 ----------
2058 ----------
2059
2059
2060 text : string
2060 text : string
2061 A string of text to be completed on. It can be given as empty and
2061 A string of text to be completed on. It can be given as empty and
2062 instead a line/position pair are given. In this case, the
2062 instead a line/position pair are given. In this case, the
2063 completer itself will split the line like readline does.
2063 completer itself will split the line like readline does.
2064
2065 line : string, optional
2064 line : string, optional
2066 The complete line that text is part of.
2065 The complete line that text is part of.
2067
2068 cursor_pos : int, optional
2066 cursor_pos : int, optional
2069 The position of the cursor on the input line.
2067 The position of the cursor on the input line.
2070
2068
2071 Returns
2069 Returns
2072 -------
2070 -------
2073 text : string
2071 text : string
2074 The actual text that was completed.
2072 The actual text that was completed.
2075
2073
2076 matches : list
2074 matches : list
2077 A sorted list with all possible completions.
2075 A sorted list with all possible completions.
2078
2076
2079
2077
2080 Notes
2078 Notes
2081 -----
2079 -----
2082 The optional arguments allow the completion to take more context into
2080 The optional arguments allow the completion to take more context into
2083 account, and are part of the low-level completion API.
2081 account, and are part of the low-level completion API.
2084
2082
2085 This is a wrapper around the completion mechanism, similar to what
2083 This is a wrapper around the completion mechanism, similar to what
2086 readline does at the command line when the TAB key is hit. By
2084 readline does at the command line when the TAB key is hit. By
2087 exposing it as a method, it can be used by other non-readline
2085 exposing it as a method, it can be used by other non-readline
2088 environments (such as GUIs) for text completion.
2086 environments (such as GUIs) for text completion.
2089
2087
2090 Examples
2088 Examples
2091 --------
2089 --------
2092
2090
2093 In [1]: x = 'hello'
2091 In [1]: x = 'hello'
2094
2092
2095 In [2]: _ip.complete('x.l')
2093 In [2]: _ip.complete('x.l')
2096 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2094 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2097 """
2095 """
2098
2096
2099 # Inject names into __builtin__ so we can complete on the added names.
2097 # Inject names into __builtin__ so we can complete on the added names.
2100 with self.builtin_trap:
2098 with self.builtin_trap:
2101 return self.Completer.complete(text, line, cursor_pos)
2099 return self.Completer.complete(text, line, cursor_pos)
2102
2100
2103 def set_custom_completer(self, completer, pos=0) -> None:
2101 def set_custom_completer(self, completer, pos=0) -> None:
2104 """Adds a new custom completer function.
2102 """Adds a new custom completer function.
2105
2103
2106 The position argument (defaults to 0) is the index in the completers
2104 The position argument (defaults to 0) is the index in the completers
2107 list where you want the completer to be inserted.
2105 list where you want the completer to be inserted.
2108
2106
2109 `completer` should have the following signature::
2107 `completer` should have the following signature::
2110
2108
2111 def completion(self: Completer, text: string) -> List[str]:
2109 def completion(self: Completer, text: string) -> List[str]:
2112 raise NotImplementedError
2110 raise NotImplementedError
2113
2111
2114 It will be bound to the current Completer instance and pass some text
2112 It will be bound to the current Completer instance and pass some text
2115 and return a list with current completions to suggest to the user.
2113 and return a list with current completions to suggest to the user.
2116 """
2114 """
2117
2115
2118 newcomp = types.MethodType(completer, self.Completer)
2116 newcomp = types.MethodType(completer, self.Completer)
2119 self.Completer.custom_matchers.insert(pos,newcomp)
2117 self.Completer.custom_matchers.insert(pos,newcomp)
2120
2118
2121 def set_completer_frame(self, frame=None):
2119 def set_completer_frame(self, frame=None):
2122 """Set the frame of the completer."""
2120 """Set the frame of the completer."""
2123 if frame:
2121 if frame:
2124 self.Completer.namespace = frame.f_locals
2122 self.Completer.namespace = frame.f_locals
2125 self.Completer.global_namespace = frame.f_globals
2123 self.Completer.global_namespace = frame.f_globals
2126 else:
2124 else:
2127 self.Completer.namespace = self.user_ns
2125 self.Completer.namespace = self.user_ns
2128 self.Completer.global_namespace = self.user_global_ns
2126 self.Completer.global_namespace = self.user_global_ns
2129
2127
2130 #-------------------------------------------------------------------------
2128 #-------------------------------------------------------------------------
2131 # Things related to magics
2129 # Things related to magics
2132 #-------------------------------------------------------------------------
2130 #-------------------------------------------------------------------------
2133
2131
2134 def init_magics(self):
2132 def init_magics(self):
2135 from IPython.core import magics as m
2133 from IPython.core import magics as m
2136 self.magics_manager = magic.MagicsManager(shell=self,
2134 self.magics_manager = magic.MagicsManager(shell=self,
2137 parent=self,
2135 parent=self,
2138 user_magics=m.UserMagics(self))
2136 user_magics=m.UserMagics(self))
2139 self.configurables.append(self.magics_manager)
2137 self.configurables.append(self.magics_manager)
2140
2138
2141 # Expose as public API from the magics manager
2139 # Expose as public API from the magics manager
2142 self.register_magics = self.magics_manager.register
2140 self.register_magics = self.magics_manager.register
2143
2141
2144 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2142 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2145 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2143 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2146 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2144 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2147 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2145 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2148 m.PylabMagics, m.ScriptMagics,
2146 m.PylabMagics, m.ScriptMagics,
2149 )
2147 )
2150 self.register_magics(m.AsyncMagics)
2148 self.register_magics(m.AsyncMagics)
2151
2149
2152 # Register Magic Aliases
2150 # Register Magic Aliases
2153 mman = self.magics_manager
2151 mman = self.magics_manager
2154 # FIXME: magic aliases should be defined by the Magics classes
2152 # FIXME: magic aliases should be defined by the Magics classes
2155 # or in MagicsManager, not here
2153 # or in MagicsManager, not here
2156 mman.register_alias('ed', 'edit')
2154 mman.register_alias('ed', 'edit')
2157 mman.register_alias('hist', 'history')
2155 mman.register_alias('hist', 'history')
2158 mman.register_alias('rep', 'recall')
2156 mman.register_alias('rep', 'recall')
2159 mman.register_alias('SVG', 'svg', 'cell')
2157 mman.register_alias('SVG', 'svg', 'cell')
2160 mman.register_alias('HTML', 'html', 'cell')
2158 mman.register_alias('HTML', 'html', 'cell')
2161 mman.register_alias('file', 'writefile', 'cell')
2159 mman.register_alias('file', 'writefile', 'cell')
2162
2160
2163 # FIXME: Move the color initialization to the DisplayHook, which
2161 # FIXME: Move the color initialization to the DisplayHook, which
2164 # should be split into a prompt manager and displayhook. We probably
2162 # should be split into a prompt manager and displayhook. We probably
2165 # even need a centralize colors management object.
2163 # even need a centralize colors management object.
2166 self.run_line_magic('colors', self.colors)
2164 self.run_line_magic('colors', self.colors)
2167
2165
2168 # Defined here so that it's included in the documentation
2166 # Defined here so that it's included in the documentation
2169 @functools.wraps(magic.MagicsManager.register_function)
2167 @functools.wraps(magic.MagicsManager.register_function)
2170 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2168 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2171 self.magics_manager.register_function(
2169 self.magics_manager.register_function(
2172 func, magic_kind=magic_kind, magic_name=magic_name
2170 func, magic_kind=magic_kind, magic_name=magic_name
2173 )
2171 )
2174
2172
2175 def run_line_magic(self, magic_name, line, _stack_depth=1):
2173 def run_line_magic(self, magic_name, line, _stack_depth=1):
2176 """Execute the given line magic.
2174 """Execute the given line magic.
2177
2175
2178 Parameters
2176 Parameters
2179 ----------
2177 ----------
2180 magic_name : str
2178 magic_name : str
2181 Name of the desired magic function, without '%' prefix.
2179 Name of the desired magic function, without '%' prefix.
2182 line : str
2180 line : str
2183 The rest of the input line as a single string.
2181 The rest of the input line as a single string.
2184 _stack_depth : int
2182 _stack_depth : int
2185 If run_line_magic() is called from magic() then _stack_depth=2.
2183 If run_line_magic() is called from magic() then _stack_depth=2.
2186 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2184 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2187 """
2185 """
2188 fn = self.find_line_magic(magic_name)
2186 fn = self.find_line_magic(magic_name)
2189 if fn is None:
2187 if fn is None:
2190 cm = self.find_cell_magic(magic_name)
2188 cm = self.find_cell_magic(magic_name)
2191 etpl = "Line magic function `%%%s` not found%s."
2189 etpl = "Line magic function `%%%s` not found%s."
2192 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2190 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2193 'did you mean that instead?)' % magic_name )
2191 'did you mean that instead?)' % magic_name )
2194 raise UsageError(etpl % (magic_name, extra))
2192 raise UsageError(etpl % (magic_name, extra))
2195 else:
2193 else:
2196 # Note: this is the distance in the stack to the user's frame.
2194 # Note: this is the distance in the stack to the user's frame.
2197 # This will need to be updated if the internal calling logic gets
2195 # This will need to be updated if the internal calling logic gets
2198 # refactored, or else we'll be expanding the wrong variables.
2196 # refactored, or else we'll be expanding the wrong variables.
2199
2197
2200 # Determine stack_depth depending on where run_line_magic() has been called
2198 # Determine stack_depth depending on where run_line_magic() has been called
2201 stack_depth = _stack_depth
2199 stack_depth = _stack_depth
2202 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2200 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2203 # magic has opted out of var_expand
2201 # magic has opted out of var_expand
2204 magic_arg_s = line
2202 magic_arg_s = line
2205 else:
2203 else:
2206 magic_arg_s = self.var_expand(line, stack_depth)
2204 magic_arg_s = self.var_expand(line, stack_depth)
2207 # Put magic args in a list so we can call with f(*a) syntax
2205 # Put magic args in a list so we can call with f(*a) syntax
2208 args = [magic_arg_s]
2206 args = [magic_arg_s]
2209 kwargs = {}
2207 kwargs = {}
2210 # Grab local namespace if we need it:
2208 # Grab local namespace if we need it:
2211 if getattr(fn, "needs_local_scope", False):
2209 if getattr(fn, "needs_local_scope", False):
2212 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2210 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2213 with self.builtin_trap:
2211 with self.builtin_trap:
2214 result = fn(*args, **kwargs)
2212 result = fn(*args, **kwargs)
2215 return result
2213 return result
2216
2214
2217 def get_local_scope(self, stack_depth):
2215 def get_local_scope(self, stack_depth):
2218 """Get local scope at given stack depth.
2216 """Get local scope at given stack depth.
2219
2217
2220 Parameters
2218 Parameters
2221 ----------
2219 ----------
2222 stack_depth : int
2220 stack_depth : int
2223 Depth relative to calling frame
2221 Depth relative to calling frame
2224 """
2222 """
2225 return sys._getframe(stack_depth + 1).f_locals
2223 return sys._getframe(stack_depth + 1).f_locals
2226
2224
2227 def run_cell_magic(self, magic_name, line, cell):
2225 def run_cell_magic(self, magic_name, line, cell):
2228 """Execute the given cell magic.
2226 """Execute the given cell magic.
2229
2227
2230 Parameters
2228 Parameters
2231 ----------
2229 ----------
2232 magic_name : str
2230 magic_name : str
2233 Name of the desired magic function, without '%' prefix.
2231 Name of the desired magic function, without '%' prefix.
2234 line : str
2232 line : str
2235 The rest of the first input line as a single string.
2233 The rest of the first input line as a single string.
2236 cell : str
2234 cell : str
2237 The body of the cell as a (possibly multiline) string.
2235 The body of the cell as a (possibly multiline) string.
2238 """
2236 """
2239 fn = self.find_cell_magic(magic_name)
2237 fn = self.find_cell_magic(magic_name)
2240 if fn is None:
2238 if fn is None:
2241 lm = self.find_line_magic(magic_name)
2239 lm = self.find_line_magic(magic_name)
2242 etpl = "Cell magic `%%{0}` not found{1}."
2240 etpl = "Cell magic `%%{0}` not found{1}."
2243 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2241 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2244 'did you mean that instead?)'.format(magic_name))
2242 'did you mean that instead?)'.format(magic_name))
2245 raise UsageError(etpl.format(magic_name, extra))
2243 raise UsageError(etpl.format(magic_name, extra))
2246 elif cell == '':
2244 elif cell == '':
2247 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2245 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2248 if self.find_line_magic(magic_name) is not None:
2246 if self.find_line_magic(magic_name) is not None:
2249 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2247 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2250 raise UsageError(message)
2248 raise UsageError(message)
2251 else:
2249 else:
2252 # Note: this is the distance in the stack to the user's frame.
2250 # Note: this is the distance in the stack to the user's frame.
2253 # This will need to be updated if the internal calling logic gets
2251 # This will need to be updated if the internal calling logic gets
2254 # refactored, or else we'll be expanding the wrong variables.
2252 # refactored, or else we'll be expanding the wrong variables.
2255 stack_depth = 2
2253 stack_depth = 2
2256 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2254 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2257 # magic has opted out of var_expand
2255 # magic has opted out of var_expand
2258 magic_arg_s = line
2256 magic_arg_s = line
2259 else:
2257 else:
2260 magic_arg_s = self.var_expand(line, stack_depth)
2258 magic_arg_s = self.var_expand(line, stack_depth)
2261 kwargs = {}
2259 kwargs = {}
2262 if getattr(fn, "needs_local_scope", False):
2260 if getattr(fn, "needs_local_scope", False):
2263 kwargs['local_ns'] = self.user_ns
2261 kwargs['local_ns'] = self.user_ns
2264
2262
2265 with self.builtin_trap:
2263 with self.builtin_trap:
2266 args = (magic_arg_s, cell)
2264 args = (magic_arg_s, cell)
2267 result = fn(*args, **kwargs)
2265 result = fn(*args, **kwargs)
2268 return result
2266 return result
2269
2267
2270 def find_line_magic(self, magic_name):
2268 def find_line_magic(self, magic_name):
2271 """Find and return a line magic by name.
2269 """Find and return a line magic by name.
2272
2270
2273 Returns None if the magic isn't found."""
2271 Returns None if the magic isn't found."""
2274 return self.magics_manager.magics['line'].get(magic_name)
2272 return self.magics_manager.magics['line'].get(magic_name)
2275
2273
2276 def find_cell_magic(self, magic_name):
2274 def find_cell_magic(self, magic_name):
2277 """Find and return a cell magic by name.
2275 """Find and return a cell magic by name.
2278
2276
2279 Returns None if the magic isn't found."""
2277 Returns None if the magic isn't found."""
2280 return self.magics_manager.magics['cell'].get(magic_name)
2278 return self.magics_manager.magics['cell'].get(magic_name)
2281
2279
2282 def find_magic(self, magic_name, magic_kind='line'):
2280 def find_magic(self, magic_name, magic_kind='line'):
2283 """Find and return a magic of the given type by name.
2281 """Find and return a magic of the given type by name.
2284
2282
2285 Returns None if the magic isn't found."""
2283 Returns None if the magic isn't found."""
2286 return self.magics_manager.magics[magic_kind].get(magic_name)
2284 return self.magics_manager.magics[magic_kind].get(magic_name)
2287
2285
2288 def magic(self, arg_s):
2286 def magic(self, arg_s):
2289 """DEPRECATED. Use run_line_magic() instead.
2287 """DEPRECATED. Use run_line_magic() instead.
2290
2288
2291 Call a magic function by name.
2289 Call a magic function by name.
2292
2290
2293 Input: a string containing the name of the magic function to call and
2291 Input: a string containing the name of the magic function to call and
2294 any additional arguments to be passed to the magic.
2292 any additional arguments to be passed to the magic.
2295
2293
2296 magic('name -opt foo bar') is equivalent to typing at the ipython
2294 magic('name -opt foo bar') is equivalent to typing at the ipython
2297 prompt:
2295 prompt:
2298
2296
2299 In[1]: %name -opt foo bar
2297 In[1]: %name -opt foo bar
2300
2298
2301 To call a magic without arguments, simply use magic('name').
2299 To call a magic without arguments, simply use magic('name').
2302
2300
2303 This provides a proper Python function to call IPython's magics in any
2301 This provides a proper Python function to call IPython's magics in any
2304 valid Python code you can type at the interpreter, including loops and
2302 valid Python code you can type at the interpreter, including loops and
2305 compound statements.
2303 compound statements.
2306 """
2304 """
2307 # TODO: should we issue a loud deprecation warning here?
2305 # TODO: should we issue a loud deprecation warning here?
2308 magic_name, _, magic_arg_s = arg_s.partition(' ')
2306 magic_name, _, magic_arg_s = arg_s.partition(' ')
2309 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2307 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2310 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2308 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2311
2309
2312 #-------------------------------------------------------------------------
2310 #-------------------------------------------------------------------------
2313 # Things related to macros
2311 # Things related to macros
2314 #-------------------------------------------------------------------------
2312 #-------------------------------------------------------------------------
2315
2313
2316 def define_macro(self, name, themacro):
2314 def define_macro(self, name, themacro):
2317 """Define a new macro
2315 """Define a new macro
2318
2316
2319 Parameters
2317 Parameters
2320 ----------
2318 ----------
2321 name : str
2319 name : str
2322 The name of the macro.
2320 The name of the macro.
2323 themacro : str or Macro
2321 themacro : str or Macro
2324 The action to do upon invoking the macro. If a string, a new
2322 The action to do upon invoking the macro. If a string, a new
2325 Macro object is created by passing the string to it.
2323 Macro object is created by passing the string to it.
2326 """
2324 """
2327
2325
2328 from IPython.core import macro
2326 from IPython.core import macro
2329
2327
2330 if isinstance(themacro, str):
2328 if isinstance(themacro, str):
2331 themacro = macro.Macro(themacro)
2329 themacro = macro.Macro(themacro)
2332 if not isinstance(themacro, macro.Macro):
2330 if not isinstance(themacro, macro.Macro):
2333 raise ValueError('A macro must be a string or a Macro instance.')
2331 raise ValueError('A macro must be a string or a Macro instance.')
2334 self.user_ns[name] = themacro
2332 self.user_ns[name] = themacro
2335
2333
2336 #-------------------------------------------------------------------------
2334 #-------------------------------------------------------------------------
2337 # Things related to the running of system commands
2335 # Things related to the running of system commands
2338 #-------------------------------------------------------------------------
2336 #-------------------------------------------------------------------------
2339
2337
2340 def system_piped(self, cmd):
2338 def system_piped(self, cmd):
2341 """Call the given cmd in a subprocess, piping stdout/err
2339 """Call the given cmd in a subprocess, piping stdout/err
2342
2340
2343 Parameters
2341 Parameters
2344 ----------
2342 ----------
2345 cmd : str
2343 cmd : str
2346 Command to execute (can not end in '&', as background processes are
2344 Command to execute (can not end in '&', as background processes are
2347 not supported. Should not be a command that expects input
2345 not supported. Should not be a command that expects input
2348 other than simple text.
2346 other than simple text.
2349 """
2347 """
2350 if cmd.rstrip().endswith('&'):
2348 if cmd.rstrip().endswith('&'):
2351 # this is *far* from a rigorous test
2349 # this is *far* from a rigorous test
2352 # We do not support backgrounding processes because we either use
2350 # We do not support backgrounding processes because we either use
2353 # pexpect or pipes to read from. Users can always just call
2351 # pexpect or pipes to read from. Users can always just call
2354 # os.system() or use ip.system=ip.system_raw
2352 # os.system() or use ip.system=ip.system_raw
2355 # if they really want a background process.
2353 # if they really want a background process.
2356 raise OSError("Background processes not supported.")
2354 raise OSError("Background processes not supported.")
2357
2355
2358 # we explicitly do NOT return the subprocess status code, because
2356 # we explicitly do NOT return the subprocess status code, because
2359 # a non-None value would trigger :func:`sys.displayhook` calls.
2357 # a non-None value would trigger :func:`sys.displayhook` calls.
2360 # Instead, we store the exit_code in user_ns.
2358 # Instead, we store the exit_code in user_ns.
2361 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2359 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2362
2360
2363 def system_raw(self, cmd):
2361 def system_raw(self, cmd):
2364 """Call the given cmd in a subprocess using os.system on Windows or
2362 """Call the given cmd in a subprocess using os.system on Windows or
2365 subprocess.call using the system shell on other platforms.
2363 subprocess.call using the system shell on other platforms.
2366
2364
2367 Parameters
2365 Parameters
2368 ----------
2366 ----------
2369 cmd : str
2367 cmd : str
2370 Command to execute.
2368 Command to execute.
2371 """
2369 """
2372 cmd = self.var_expand(cmd, depth=1)
2370 cmd = self.var_expand(cmd, depth=1)
2373 # warn if there is an IPython magic alternative.
2371 # warn if there is an IPython magic alternative.
2374 main_cmd = cmd.split()[0]
2372 main_cmd = cmd.split()[0]
2375 has_magic_alternatives = ("pip", "conda", "cd", "ls")
2373 has_magic_alternatives = ("pip", "conda", "cd", "ls")
2376
2374
2377 # had to check if the command was an alias expanded because of `ls`
2375 # had to check if the command was an alias expanded because of `ls`
2378 is_alias_expanded = self.alias_manager.is_alias(main_cmd) and (
2376 is_alias_expanded = self.alias_manager.is_alias(main_cmd) and (
2379 self.alias_manager.retrieve_alias(main_cmd).strip() == cmd.strip()
2377 self.alias_manager.retrieve_alias(main_cmd).strip() == cmd.strip()
2380 )
2378 )
2381
2379
2382 if main_cmd in has_magic_alternatives and not is_alias_expanded:
2380 if main_cmd in has_magic_alternatives and not is_alias_expanded:
2383 warnings.warn(
2381 warnings.warn(
2384 (
2382 (
2385 "You executed the system command !{0} which may not work "
2383 "You executed the system command !{0} which may not work "
2386 "as expected. Try the IPython magic %{0} instead."
2384 "as expected. Try the IPython magic %{0} instead."
2387 ).format(main_cmd)
2385 ).format(main_cmd)
2388 )
2386 )
2389
2387
2390 # protect os.system from UNC paths on Windows, which it can't handle:
2388 # protect os.system from UNC paths on Windows, which it can't handle:
2391 if sys.platform == 'win32':
2389 if sys.platform == 'win32':
2392 from IPython.utils._process_win32 import AvoidUNCPath
2390 from IPython.utils._process_win32 import AvoidUNCPath
2393 with AvoidUNCPath() as path:
2391 with AvoidUNCPath() as path:
2394 if path is not None:
2392 if path is not None:
2395 cmd = '"pushd %s &&"%s' % (path, cmd)
2393 cmd = '"pushd %s &&"%s' % (path, cmd)
2396 try:
2394 try:
2397 ec = os.system(cmd)
2395 ec = os.system(cmd)
2398 except KeyboardInterrupt:
2396 except KeyboardInterrupt:
2399 print('\n' + self.get_exception_only(), file=sys.stderr)
2397 print('\n' + self.get_exception_only(), file=sys.stderr)
2400 ec = -2
2398 ec = -2
2401 else:
2399 else:
2402 # For posix the result of the subprocess.call() below is an exit
2400 # For posix the result of the subprocess.call() below is an exit
2403 # code, which by convention is zero for success, positive for
2401 # code, which by convention is zero for success, positive for
2404 # program failure. Exit codes above 128 are reserved for signals,
2402 # program failure. Exit codes above 128 are reserved for signals,
2405 # and the formula for converting a signal to an exit code is usually
2403 # and the formula for converting a signal to an exit code is usually
2406 # signal_number+128. To more easily differentiate between exit
2404 # signal_number+128. To more easily differentiate between exit
2407 # codes and signals, ipython uses negative numbers. For instance
2405 # codes and signals, ipython uses negative numbers. For instance
2408 # since control-c is signal 2 but exit code 130, ipython's
2406 # since control-c is signal 2 but exit code 130, ipython's
2409 # _exit_code variable will read -2. Note that some shells like
2407 # _exit_code variable will read -2. Note that some shells like
2410 # csh and fish don't follow sh/bash conventions for exit codes.
2408 # csh and fish don't follow sh/bash conventions for exit codes.
2411 executable = os.environ.get('SHELL', None)
2409 executable = os.environ.get('SHELL', None)
2412 try:
2410 try:
2413 # Use env shell instead of default /bin/sh
2411 # Use env shell instead of default /bin/sh
2414 ec = subprocess.call(cmd, shell=True, executable=executable)
2412 ec = subprocess.call(cmd, shell=True, executable=executable)
2415 except KeyboardInterrupt:
2413 except KeyboardInterrupt:
2416 # intercept control-C; a long traceback is not useful here
2414 # intercept control-C; a long traceback is not useful here
2417 print('\n' + self.get_exception_only(), file=sys.stderr)
2415 print('\n' + self.get_exception_only(), file=sys.stderr)
2418 ec = 130
2416 ec = 130
2419 if ec > 128:
2417 if ec > 128:
2420 ec = -(ec - 128)
2418 ec = -(ec - 128)
2421
2419
2422 # We explicitly do NOT return the subprocess status code, because
2420 # We explicitly do NOT return the subprocess status code, because
2423 # a non-None value would trigger :func:`sys.displayhook` calls.
2421 # a non-None value would trigger :func:`sys.displayhook` calls.
2424 # Instead, we store the exit_code in user_ns. Note the semantics
2422 # Instead, we store the exit_code in user_ns. Note the semantics
2425 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2423 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2426 # but raising SystemExit(_exit_code) will give status 254!
2424 # but raising SystemExit(_exit_code) will give status 254!
2427 self.user_ns['_exit_code'] = ec
2425 self.user_ns['_exit_code'] = ec
2428
2426
2429 # use piped system by default, because it is better behaved
2427 # use piped system by default, because it is better behaved
2430 system = system_piped
2428 system = system_piped
2431
2429
2432 def getoutput(self, cmd, split=True, depth=0):
2430 def getoutput(self, cmd, split=True, depth=0):
2433 """Get output (possibly including stderr) from a subprocess.
2431 """Get output (possibly including stderr) from a subprocess.
2434
2432
2435 Parameters
2433 Parameters
2436 ----------
2434 ----------
2437 cmd : str
2435 cmd : str
2438 Command to execute (can not end in '&', as background processes are
2436 Command to execute (can not end in '&', as background processes are
2439 not supported.
2437 not supported.
2440 split : bool, optional
2438 split : bool, optional
2441 If True, split the output into an IPython SList. Otherwise, an
2439 If True, split the output into an IPython SList. Otherwise, an
2442 IPython LSString is returned. These are objects similar to normal
2440 IPython LSString is returned. These are objects similar to normal
2443 lists and strings, with a few convenience attributes for easier
2441 lists and strings, with a few convenience attributes for easier
2444 manipulation of line-based output. You can use '?' on them for
2442 manipulation of line-based output. You can use '?' on them for
2445 details.
2443 details.
2446 depth : int, optional
2444 depth : int, optional
2447 How many frames above the caller are the local variables which should
2445 How many frames above the caller are the local variables which should
2448 be expanded in the command string? The default (0) assumes that the
2446 be expanded in the command string? The default (0) assumes that the
2449 expansion variables are in the stack frame calling this function.
2447 expansion variables are in the stack frame calling this function.
2450 """
2448 """
2451 if cmd.rstrip().endswith('&'):
2449 if cmd.rstrip().endswith('&'):
2452 # this is *far* from a rigorous test
2450 # this is *far* from a rigorous test
2453 raise OSError("Background processes not supported.")
2451 raise OSError("Background processes not supported.")
2454 out = getoutput(self.var_expand(cmd, depth=depth+1))
2452 out = getoutput(self.var_expand(cmd, depth=depth+1))
2455 if split:
2453 if split:
2456 out = SList(out.splitlines())
2454 out = SList(out.splitlines())
2457 else:
2455 else:
2458 out = LSString(out)
2456 out = LSString(out)
2459 return out
2457 return out
2460
2458
2461 #-------------------------------------------------------------------------
2459 #-------------------------------------------------------------------------
2462 # Things related to aliases
2460 # Things related to aliases
2463 #-------------------------------------------------------------------------
2461 #-------------------------------------------------------------------------
2464
2462
2465 def init_alias(self):
2463 def init_alias(self):
2466 self.alias_manager = AliasManager(shell=self, parent=self)
2464 self.alias_manager = AliasManager(shell=self, parent=self)
2467 self.configurables.append(self.alias_manager)
2465 self.configurables.append(self.alias_manager)
2468
2466
2469 #-------------------------------------------------------------------------
2467 #-------------------------------------------------------------------------
2470 # Things related to extensions
2468 # Things related to extensions
2471 #-------------------------------------------------------------------------
2469 #-------------------------------------------------------------------------
2472
2470
2473 def init_extension_manager(self):
2471 def init_extension_manager(self):
2474 self.extension_manager = ExtensionManager(shell=self, parent=self)
2472 self.extension_manager = ExtensionManager(shell=self, parent=self)
2475 self.configurables.append(self.extension_manager)
2473 self.configurables.append(self.extension_manager)
2476
2474
2477 #-------------------------------------------------------------------------
2475 #-------------------------------------------------------------------------
2478 # Things related to payloads
2476 # Things related to payloads
2479 #-------------------------------------------------------------------------
2477 #-------------------------------------------------------------------------
2480
2478
2481 def init_payload(self):
2479 def init_payload(self):
2482 self.payload_manager = PayloadManager(parent=self)
2480 self.payload_manager = PayloadManager(parent=self)
2483 self.configurables.append(self.payload_manager)
2481 self.configurables.append(self.payload_manager)
2484
2482
2485 #-------------------------------------------------------------------------
2483 #-------------------------------------------------------------------------
2486 # Things related to the prefilter
2484 # Things related to the prefilter
2487 #-------------------------------------------------------------------------
2485 #-------------------------------------------------------------------------
2488
2486
2489 def init_prefilter(self):
2487 def init_prefilter(self):
2490 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2488 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2491 self.configurables.append(self.prefilter_manager)
2489 self.configurables.append(self.prefilter_manager)
2492 # Ultimately this will be refactored in the new interpreter code, but
2490 # Ultimately this will be refactored in the new interpreter code, but
2493 # for now, we should expose the main prefilter method (there's legacy
2491 # for now, we should expose the main prefilter method (there's legacy
2494 # code out there that may rely on this).
2492 # code out there that may rely on this).
2495 self.prefilter = self.prefilter_manager.prefilter_lines
2493 self.prefilter = self.prefilter_manager.prefilter_lines
2496
2494
2497 def auto_rewrite_input(self, cmd):
2495 def auto_rewrite_input(self, cmd):
2498 """Print to the screen the rewritten form of the user's command.
2496 """Print to the screen the rewritten form of the user's command.
2499
2497
2500 This shows visual feedback by rewriting input lines that cause
2498 This shows visual feedback by rewriting input lines that cause
2501 automatic calling to kick in, like::
2499 automatic calling to kick in, like::
2502
2500
2503 /f x
2501 /f x
2504
2502
2505 into::
2503 into::
2506
2504
2507 ------> f(x)
2505 ------> f(x)
2508
2506
2509 after the user's input prompt. This helps the user understand that the
2507 after the user's input prompt. This helps the user understand that the
2510 input line was transformed automatically by IPython.
2508 input line was transformed automatically by IPython.
2511 """
2509 """
2512 if not self.show_rewritten_input:
2510 if not self.show_rewritten_input:
2513 return
2511 return
2514
2512
2515 # This is overridden in TerminalInteractiveShell to use fancy prompts
2513 # This is overridden in TerminalInteractiveShell to use fancy prompts
2516 print("------> " + cmd)
2514 print("------> " + cmd)
2517
2515
2518 #-------------------------------------------------------------------------
2516 #-------------------------------------------------------------------------
2519 # Things related to extracting values/expressions from kernel and user_ns
2517 # Things related to extracting values/expressions from kernel and user_ns
2520 #-------------------------------------------------------------------------
2518 #-------------------------------------------------------------------------
2521
2519
2522 def _user_obj_error(self):
2520 def _user_obj_error(self):
2523 """return simple exception dict
2521 """return simple exception dict
2524
2522
2525 for use in user_expressions
2523 for use in user_expressions
2526 """
2524 """
2527
2525
2528 etype, evalue, tb = self._get_exc_info()
2526 etype, evalue, tb = self._get_exc_info()
2529 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2527 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2530
2528
2531 exc_info = {
2529 exc_info = {
2532 "status": "error",
2530 "status": "error",
2533 "traceback": stb,
2531 "traceback": stb,
2534 "ename": etype.__name__,
2532 "ename": etype.__name__,
2535 "evalue": py3compat.safe_unicode(evalue),
2533 "evalue": py3compat.safe_unicode(evalue),
2536 }
2534 }
2537
2535
2538 return exc_info
2536 return exc_info
2539
2537
2540 def _format_user_obj(self, obj):
2538 def _format_user_obj(self, obj):
2541 """format a user object to display dict
2539 """format a user object to display dict
2542
2540
2543 for use in user_expressions
2541 for use in user_expressions
2544 """
2542 """
2545
2543
2546 data, md = self.display_formatter.format(obj)
2544 data, md = self.display_formatter.format(obj)
2547 value = {
2545 value = {
2548 'status' : 'ok',
2546 'status' : 'ok',
2549 'data' : data,
2547 'data' : data,
2550 'metadata' : md,
2548 'metadata' : md,
2551 }
2549 }
2552 return value
2550 return value
2553
2551
2554 def user_expressions(self, expressions):
2552 def user_expressions(self, expressions):
2555 """Evaluate a dict of expressions in the user's namespace.
2553 """Evaluate a dict of expressions in the user's namespace.
2556
2554
2557 Parameters
2555 Parameters
2558 ----------
2556 ----------
2559 expressions : dict
2557 expressions : dict
2560 A dict with string keys and string values. The expression values
2558 A dict with string keys and string values. The expression values
2561 should be valid Python expressions, each of which will be evaluated
2559 should be valid Python expressions, each of which will be evaluated
2562 in the user namespace.
2560 in the user namespace.
2563
2561
2564 Returns
2562 Returns
2565 -------
2563 -------
2566 A dict, keyed like the input expressions dict, with the rich mime-typed
2564 A dict, keyed like the input expressions dict, with the rich mime-typed
2567 display_data of each value.
2565 display_data of each value.
2568 """
2566 """
2569 out = {}
2567 out = {}
2570 user_ns = self.user_ns
2568 user_ns = self.user_ns
2571 global_ns = self.user_global_ns
2569 global_ns = self.user_global_ns
2572
2570
2573 for key, expr in expressions.items():
2571 for key, expr in expressions.items():
2574 try:
2572 try:
2575 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2573 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2576 except:
2574 except:
2577 value = self._user_obj_error()
2575 value = self._user_obj_error()
2578 out[key] = value
2576 out[key] = value
2579 return out
2577 return out
2580
2578
2581 #-------------------------------------------------------------------------
2579 #-------------------------------------------------------------------------
2582 # Things related to the running of code
2580 # Things related to the running of code
2583 #-------------------------------------------------------------------------
2581 #-------------------------------------------------------------------------
2584
2582
2585 def ex(self, cmd):
2583 def ex(self, cmd):
2586 """Execute a normal python statement in user namespace."""
2584 """Execute a normal python statement in user namespace."""
2587 with self.builtin_trap:
2585 with self.builtin_trap:
2588 exec(cmd, self.user_global_ns, self.user_ns)
2586 exec(cmd, self.user_global_ns, self.user_ns)
2589
2587
2590 def ev(self, expr):
2588 def ev(self, expr):
2591 """Evaluate python expression expr in user namespace.
2589 """Evaluate python expression expr in user namespace.
2592
2590
2593 Returns the result of evaluation
2591 Returns the result of evaluation
2594 """
2592 """
2595 with self.builtin_trap:
2593 with self.builtin_trap:
2596 return eval(expr, self.user_global_ns, self.user_ns)
2594 return eval(expr, self.user_global_ns, self.user_ns)
2597
2595
2598 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2596 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2599 """A safe version of the builtin execfile().
2597 """A safe version of the builtin execfile().
2600
2598
2601 This version will never throw an exception, but instead print
2599 This version will never throw an exception, but instead print
2602 helpful error messages to the screen. This only works on pure
2600 helpful error messages to the screen. This only works on pure
2603 Python files with the .py extension.
2601 Python files with the .py extension.
2604
2602
2605 Parameters
2603 Parameters
2606 ----------
2604 ----------
2607 fname : string
2605 fname : string
2608 The name of the file to be executed.
2606 The name of the file to be executed.
2609 where : tuple
2607 *where : tuple
2610 One or two namespaces, passed to execfile() as (globals,locals).
2608 One or two namespaces, passed to execfile() as (globals,locals).
2611 If only one is given, it is passed as both.
2609 If only one is given, it is passed as both.
2612 exit_ignore : bool (False)
2610 exit_ignore : bool (False)
2613 If True, then silence SystemExit for non-zero status (it is always
2611 If True, then silence SystemExit for non-zero status (it is always
2614 silenced for zero status, as it is so common).
2612 silenced for zero status, as it is so common).
2615 raise_exceptions : bool (False)
2613 raise_exceptions : bool (False)
2616 If True raise exceptions everywhere. Meant for testing.
2614 If True raise exceptions everywhere. Meant for testing.
2617 shell_futures : bool (False)
2615 shell_futures : bool (False)
2618 If True, the code will share future statements with the interactive
2616 If True, the code will share future statements with the interactive
2619 shell. It will both be affected by previous __future__ imports, and
2617 shell. It will both be affected by previous __future__ imports, and
2620 any __future__ imports in the code will affect the shell. If False,
2618 any __future__ imports in the code will affect the shell. If False,
2621 __future__ imports are not shared in either direction.
2619 __future__ imports are not shared in either direction.
2622
2620
2623 """
2621 """
2624 fname = Path(fname).expanduser().resolve()
2622 fname = Path(fname).expanduser().resolve()
2625
2623
2626 # Make sure we can open the file
2624 # Make sure we can open the file
2627 try:
2625 try:
2628 with fname.open():
2626 with fname.open():
2629 pass
2627 pass
2630 except:
2628 except:
2631 warn('Could not open file <%s> for safe execution.' % fname)
2629 warn('Could not open file <%s> for safe execution.' % fname)
2632 return
2630 return
2633
2631
2634 # Find things also in current directory. This is needed to mimic the
2632 # Find things also in current directory. This is needed to mimic the
2635 # behavior of running a script from the system command line, where
2633 # behavior of running a script from the system command line, where
2636 # Python inserts the script's directory into sys.path
2634 # Python inserts the script's directory into sys.path
2637 dname = str(fname.parent)
2635 dname = str(fname.parent)
2638
2636
2639 with prepended_to_syspath(dname), self.builtin_trap:
2637 with prepended_to_syspath(dname), self.builtin_trap:
2640 try:
2638 try:
2641 glob, loc = (where + (None, ))[:2]
2639 glob, loc = (where + (None, ))[:2]
2642 py3compat.execfile(
2640 py3compat.execfile(
2643 fname, glob, loc,
2641 fname, glob, loc,
2644 self.compile if shell_futures else None)
2642 self.compile if shell_futures else None)
2645 except SystemExit as status:
2643 except SystemExit as status:
2646 # If the call was made with 0 or None exit status (sys.exit(0)
2644 # If the call was made with 0 or None exit status (sys.exit(0)
2647 # or sys.exit() ), don't bother showing a traceback, as both of
2645 # or sys.exit() ), don't bother showing a traceback, as both of
2648 # these are considered normal by the OS:
2646 # these are considered normal by the OS:
2649 # > python -c'import sys;sys.exit(0)'; echo $?
2647 # > python -c'import sys;sys.exit(0)'; echo $?
2650 # 0
2648 # 0
2651 # > python -c'import sys;sys.exit()'; echo $?
2649 # > python -c'import sys;sys.exit()'; echo $?
2652 # 0
2650 # 0
2653 # For other exit status, we show the exception unless
2651 # For other exit status, we show the exception unless
2654 # explicitly silenced, but only in short form.
2652 # explicitly silenced, but only in short form.
2655 if status.code:
2653 if status.code:
2656 if raise_exceptions:
2654 if raise_exceptions:
2657 raise
2655 raise
2658 if not exit_ignore:
2656 if not exit_ignore:
2659 self.showtraceback(exception_only=True)
2657 self.showtraceback(exception_only=True)
2660 except:
2658 except:
2661 if raise_exceptions:
2659 if raise_exceptions:
2662 raise
2660 raise
2663 # tb offset is 2 because we wrap execfile
2661 # tb offset is 2 because we wrap execfile
2664 self.showtraceback(tb_offset=2)
2662 self.showtraceback(tb_offset=2)
2665
2663
2666 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2664 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2667 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2665 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2668
2666
2669 Parameters
2667 Parameters
2670 ----------
2668 ----------
2671 fname : str
2669 fname : str
2672 The name of the file to execute. The filename must have a
2670 The name of the file to execute. The filename must have a
2673 .ipy or .ipynb extension.
2671 .ipy or .ipynb extension.
2674 shell_futures : bool (False)
2672 shell_futures : bool (False)
2675 If True, the code will share future statements with the interactive
2673 If True, the code will share future statements with the interactive
2676 shell. It will both be affected by previous __future__ imports, and
2674 shell. It will both be affected by previous __future__ imports, and
2677 any __future__ imports in the code will affect the shell. If False,
2675 any __future__ imports in the code will affect the shell. If False,
2678 __future__ imports are not shared in either direction.
2676 __future__ imports are not shared in either direction.
2679 raise_exceptions : bool (False)
2677 raise_exceptions : bool (False)
2680 If True raise exceptions everywhere. Meant for testing.
2678 If True raise exceptions everywhere. Meant for testing.
2681 """
2679 """
2682 fname = Path(fname).expanduser().resolve()
2680 fname = Path(fname).expanduser().resolve()
2683
2681
2684 # Make sure we can open the file
2682 # Make sure we can open the file
2685 try:
2683 try:
2686 with fname.open():
2684 with fname.open():
2687 pass
2685 pass
2688 except:
2686 except:
2689 warn('Could not open file <%s> for safe execution.' % fname)
2687 warn('Could not open file <%s> for safe execution.' % fname)
2690 return
2688 return
2691
2689
2692 # Find things also in current directory. This is needed to mimic the
2690 # Find things also in current directory. This is needed to mimic the
2693 # behavior of running a script from the system command line, where
2691 # behavior of running a script from the system command line, where
2694 # Python inserts the script's directory into sys.path
2692 # Python inserts the script's directory into sys.path
2695 dname = str(fname.parent)
2693 dname = str(fname.parent)
2696
2694
2697 def get_cells():
2695 def get_cells():
2698 """generator for sequence of code blocks to run"""
2696 """generator for sequence of code blocks to run"""
2699 if fname.suffix == ".ipynb":
2697 if fname.suffix == ".ipynb":
2700 from nbformat import read
2698 from nbformat import read
2701 nb = read(fname, as_version=4)
2699 nb = read(fname, as_version=4)
2702 if not nb.cells:
2700 if not nb.cells:
2703 return
2701 return
2704 for cell in nb.cells:
2702 for cell in nb.cells:
2705 if cell.cell_type == 'code':
2703 if cell.cell_type == 'code':
2706 yield cell.source
2704 yield cell.source
2707 else:
2705 else:
2708 yield fname.read_text()
2706 yield fname.read_text()
2709
2707
2710 with prepended_to_syspath(dname):
2708 with prepended_to_syspath(dname):
2711 try:
2709 try:
2712 for cell in get_cells():
2710 for cell in get_cells():
2713 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2711 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2714 if raise_exceptions:
2712 if raise_exceptions:
2715 result.raise_error()
2713 result.raise_error()
2716 elif not result.success:
2714 elif not result.success:
2717 break
2715 break
2718 except:
2716 except:
2719 if raise_exceptions:
2717 if raise_exceptions:
2720 raise
2718 raise
2721 self.showtraceback()
2719 self.showtraceback()
2722 warn('Unknown failure executing file: <%s>' % fname)
2720 warn('Unknown failure executing file: <%s>' % fname)
2723
2721
2724 def safe_run_module(self, mod_name, where):
2722 def safe_run_module(self, mod_name, where):
2725 """A safe version of runpy.run_module().
2723 """A safe version of runpy.run_module().
2726
2724
2727 This version will never throw an exception, but instead print
2725 This version will never throw an exception, but instead print
2728 helpful error messages to the screen.
2726 helpful error messages to the screen.
2729
2727
2730 `SystemExit` exceptions with status code 0 or None are ignored.
2728 `SystemExit` exceptions with status code 0 or None are ignored.
2731
2729
2732 Parameters
2730 Parameters
2733 ----------
2731 ----------
2734 mod_name : string
2732 mod_name : string
2735 The name of the module to be executed.
2733 The name of the module to be executed.
2736 where : dict
2734 where : dict
2737 The globals namespace.
2735 The globals namespace.
2738 """
2736 """
2739 try:
2737 try:
2740 try:
2738 try:
2741 where.update(
2739 where.update(
2742 runpy.run_module(str(mod_name), run_name="__main__",
2740 runpy.run_module(str(mod_name), run_name="__main__",
2743 alter_sys=True)
2741 alter_sys=True)
2744 )
2742 )
2745 except SystemExit as status:
2743 except SystemExit as status:
2746 if status.code:
2744 if status.code:
2747 raise
2745 raise
2748 except:
2746 except:
2749 self.showtraceback()
2747 self.showtraceback()
2750 warn('Unknown failure executing module: <%s>' % mod_name)
2748 warn('Unknown failure executing module: <%s>' % mod_name)
2751
2749
2752 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2750 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2753 """Run a complete IPython cell.
2751 """Run a complete IPython cell.
2754
2752
2755 Parameters
2753 Parameters
2756 ----------
2754 ----------
2757 raw_cell : str
2755 raw_cell : str
2758 The code (including IPython code such as %magic functions) to run.
2756 The code (including IPython code such as %magic functions) to run.
2759 store_history : bool
2757 store_history : bool
2760 If True, the raw and translated cell will be stored in IPython's
2758 If True, the raw and translated cell will be stored in IPython's
2761 history. For user code calling back into IPython's machinery, this
2759 history. For user code calling back into IPython's machinery, this
2762 should be set to False.
2760 should be set to False.
2763 silent : bool
2761 silent : bool
2764 If True, avoid side-effects, such as implicit displayhooks and
2762 If True, avoid side-effects, such as implicit displayhooks and
2765 and logging. silent=True forces store_history=False.
2763 and logging. silent=True forces store_history=False.
2766 shell_futures : bool
2764 shell_futures : bool
2767 If True, the code will share future statements with the interactive
2765 If True, the code will share future statements with the interactive
2768 shell. It will both be affected by previous __future__ imports, and
2766 shell. It will both be affected by previous __future__ imports, and
2769 any __future__ imports in the code will affect the shell. If False,
2767 any __future__ imports in the code will affect the shell. If False,
2770 __future__ imports are not shared in either direction.
2768 __future__ imports are not shared in either direction.
2771
2769
2772 Returns
2770 Returns
2773 -------
2771 -------
2774 result : :class:`ExecutionResult`
2772 result : :class:`ExecutionResult`
2775 """
2773 """
2776 result = None
2774 result = None
2777 try:
2775 try:
2778 result = self._run_cell(
2776 result = self._run_cell(
2779 raw_cell, store_history, silent, shell_futures)
2777 raw_cell, store_history, silent, shell_futures)
2780 finally:
2778 finally:
2781 self.events.trigger('post_execute')
2779 self.events.trigger('post_execute')
2782 if not silent:
2780 if not silent:
2783 self.events.trigger('post_run_cell', result)
2781 self.events.trigger('post_run_cell', result)
2784 return result
2782 return result
2785
2783
2786 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool) -> ExecutionResult:
2784 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool) -> ExecutionResult:
2787 """Internal method to run a complete IPython cell."""
2785 """Internal method to run a complete IPython cell."""
2788
2786
2789 # we need to avoid calling self.transform_cell multiple time on the same thing
2787 # we need to avoid calling self.transform_cell multiple time on the same thing
2790 # so we need to store some results:
2788 # so we need to store some results:
2791 preprocessing_exc_tuple = None
2789 preprocessing_exc_tuple = None
2792 try:
2790 try:
2793 transformed_cell = self.transform_cell(raw_cell)
2791 transformed_cell = self.transform_cell(raw_cell)
2794 except Exception:
2792 except Exception:
2795 transformed_cell = raw_cell
2793 transformed_cell = raw_cell
2796 preprocessing_exc_tuple = sys.exc_info()
2794 preprocessing_exc_tuple = sys.exc_info()
2797
2795
2798 assert transformed_cell is not None
2796 assert transformed_cell is not None
2799 coro = self.run_cell_async(
2797 coro = self.run_cell_async(
2800 raw_cell,
2798 raw_cell,
2801 store_history=store_history,
2799 store_history=store_history,
2802 silent=silent,
2800 silent=silent,
2803 shell_futures=shell_futures,
2801 shell_futures=shell_futures,
2804 transformed_cell=transformed_cell,
2802 transformed_cell=transformed_cell,
2805 preprocessing_exc_tuple=preprocessing_exc_tuple,
2803 preprocessing_exc_tuple=preprocessing_exc_tuple,
2806 )
2804 )
2807
2805
2808 # run_cell_async is async, but may not actually need an eventloop.
2806 # run_cell_async is async, but may not actually need an eventloop.
2809 # when this is the case, we want to run it using the pseudo_sync_runner
2807 # when this is the case, we want to run it using the pseudo_sync_runner
2810 # so that code can invoke eventloops (for example via the %run , and
2808 # so that code can invoke eventloops (for example via the %run , and
2811 # `%paste` magic.
2809 # `%paste` magic.
2812 if self.trio_runner:
2810 if self.trio_runner:
2813 runner = self.trio_runner
2811 runner = self.trio_runner
2814 elif self.should_run_async(
2812 elif self.should_run_async(
2815 raw_cell,
2813 raw_cell,
2816 transformed_cell=transformed_cell,
2814 transformed_cell=transformed_cell,
2817 preprocessing_exc_tuple=preprocessing_exc_tuple,
2815 preprocessing_exc_tuple=preprocessing_exc_tuple,
2818 ):
2816 ):
2819 runner = self.loop_runner
2817 runner = self.loop_runner
2820 else:
2818 else:
2821 runner = _pseudo_sync_runner
2819 runner = _pseudo_sync_runner
2822
2820
2823 try:
2821 try:
2824 return runner(coro)
2822 return runner(coro)
2825 except BaseException as e:
2823 except BaseException as e:
2826 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
2824 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
2827 result = ExecutionResult(info)
2825 result = ExecutionResult(info)
2828 result.error_in_exec = e
2826 result.error_in_exec = e
2829 self.showtraceback(running_compiled_code=True)
2827 self.showtraceback(running_compiled_code=True)
2830 return result
2828 return result
2831
2829
2832 def should_run_async(
2830 def should_run_async(
2833 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
2831 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
2834 ) -> bool:
2832 ) -> bool:
2835 """Return whether a cell should be run asynchronously via a coroutine runner
2833 """Return whether a cell should be run asynchronously via a coroutine runner
2836
2834
2837 Parameters
2835 Parameters
2838 ----------
2836 ----------
2839 raw_cell: str
2837 raw_cell: str
2840 The code to be executed
2838 The code to be executed
2841
2839
2842 Returns
2840 Returns
2843 -------
2841 -------
2844 result: bool
2842 result: bool
2845 Whether the code needs to be run with a coroutine runner or not
2843 Whether the code needs to be run with a coroutine runner or not
2846
2844
2847 .. versionadded:: 7.0
2845 .. versionadded:: 7.0
2848 """
2846 """
2849 if not self.autoawait:
2847 if not self.autoawait:
2850 return False
2848 return False
2851 if preprocessing_exc_tuple is not None:
2849 if preprocessing_exc_tuple is not None:
2852 return False
2850 return False
2853 assert preprocessing_exc_tuple is None
2851 assert preprocessing_exc_tuple is None
2854 if transformed_cell is None:
2852 if transformed_cell is None:
2855 warnings.warn(
2853 warnings.warn(
2856 "`should_run_async` will not call `transform_cell`"
2854 "`should_run_async` will not call `transform_cell`"
2857 " automatically in the future. Please pass the result to"
2855 " automatically in the future. Please pass the result to"
2858 " `transformed_cell` argument and any exception that happen"
2856 " `transformed_cell` argument and any exception that happen"
2859 " during the"
2857 " during the"
2860 "transform in `preprocessing_exc_tuple` in"
2858 "transform in `preprocessing_exc_tuple` in"
2861 " IPython 7.17 and above.",
2859 " IPython 7.17 and above.",
2862 DeprecationWarning,
2860 DeprecationWarning,
2863 stacklevel=2,
2861 stacklevel=2,
2864 )
2862 )
2865 try:
2863 try:
2866 cell = self.transform_cell(raw_cell)
2864 cell = self.transform_cell(raw_cell)
2867 except Exception:
2865 except Exception:
2868 # any exception during transform will be raised
2866 # any exception during transform will be raised
2869 # prior to execution
2867 # prior to execution
2870 return False
2868 return False
2871 else:
2869 else:
2872 cell = transformed_cell
2870 cell = transformed_cell
2873 return _should_be_async(cell)
2871 return _should_be_async(cell)
2874
2872
2875 async def run_cell_async(
2873 async def run_cell_async(
2876 self,
2874 self,
2877 raw_cell: str,
2875 raw_cell: str,
2878 store_history=False,
2876 store_history=False,
2879 silent=False,
2877 silent=False,
2880 shell_futures=True,
2878 shell_futures=True,
2881 *,
2879 *,
2882 transformed_cell: Optional[str] = None,
2880 transformed_cell: Optional[str] = None,
2883 preprocessing_exc_tuple: Optional[Any] = None
2881 preprocessing_exc_tuple: Optional[Any] = None
2884 ) -> ExecutionResult:
2882 ) -> ExecutionResult:
2885 """Run a complete IPython cell asynchronously.
2883 """Run a complete IPython cell asynchronously.
2886
2884
2887 Parameters
2885 Parameters
2888 ----------
2886 ----------
2889 raw_cell : str
2887 raw_cell : str
2890 The code (including IPython code such as %magic functions) to run.
2888 The code (including IPython code such as %magic functions) to run.
2891 store_history : bool
2889 store_history : bool
2892 If True, the raw and translated cell will be stored in IPython's
2890 If True, the raw and translated cell will be stored in IPython's
2893 history. For user code calling back into IPython's machinery, this
2891 history. For user code calling back into IPython's machinery, this
2894 should be set to False.
2892 should be set to False.
2895 silent : bool
2893 silent : bool
2896 If True, avoid side-effects, such as implicit displayhooks and
2894 If True, avoid side-effects, such as implicit displayhooks and
2897 and logging. silent=True forces store_history=False.
2895 and logging. silent=True forces store_history=False.
2898 shell_futures : bool
2896 shell_futures : bool
2899 If True, the code will share future statements with the interactive
2897 If True, the code will share future statements with the interactive
2900 shell. It will both be affected by previous __future__ imports, and
2898 shell. It will both be affected by previous __future__ imports, and
2901 any __future__ imports in the code will affect the shell. If False,
2899 any __future__ imports in the code will affect the shell. If False,
2902 __future__ imports are not shared in either direction.
2900 __future__ imports are not shared in either direction.
2903 transformed_cell: str
2901 transformed_cell: str
2904 cell that was passed through transformers
2902 cell that was passed through transformers
2905 preprocessing_exc_tuple:
2903 preprocessing_exc_tuple:
2906 trace if the transformation failed.
2904 trace if the transformation failed.
2907
2905
2908 Returns
2906 Returns
2909 -------
2907 -------
2910 result : :class:`ExecutionResult`
2908 result : :class:`ExecutionResult`
2911
2909
2912 .. versionadded:: 7.0
2910 .. versionadded:: 7.0
2913 """
2911 """
2914 info = ExecutionInfo(
2912 info = ExecutionInfo(
2915 raw_cell, store_history, silent, shell_futures)
2913 raw_cell, store_history, silent, shell_futures)
2916 result = ExecutionResult(info)
2914 result = ExecutionResult(info)
2917
2915
2918 if (not raw_cell) or raw_cell.isspace():
2916 if (not raw_cell) or raw_cell.isspace():
2919 self.last_execution_succeeded = True
2917 self.last_execution_succeeded = True
2920 self.last_execution_result = result
2918 self.last_execution_result = result
2921 return result
2919 return result
2922
2920
2923 if silent:
2921 if silent:
2924 store_history = False
2922 store_history = False
2925
2923
2926 if store_history:
2924 if store_history:
2927 result.execution_count = self.execution_count
2925 result.execution_count = self.execution_count
2928
2926
2929 def error_before_exec(value):
2927 def error_before_exec(value):
2930 if store_history:
2928 if store_history:
2931 self.execution_count += 1
2929 self.execution_count += 1
2932 result.error_before_exec = value
2930 result.error_before_exec = value
2933 self.last_execution_succeeded = False
2931 self.last_execution_succeeded = False
2934 self.last_execution_result = result
2932 self.last_execution_result = result
2935 return result
2933 return result
2936
2934
2937 self.events.trigger('pre_execute')
2935 self.events.trigger('pre_execute')
2938 if not silent:
2936 if not silent:
2939 self.events.trigger('pre_run_cell', info)
2937 self.events.trigger('pre_run_cell', info)
2940
2938
2941 if transformed_cell is None:
2939 if transformed_cell is None:
2942 warnings.warn(
2940 warnings.warn(
2943 "`run_cell_async` will not call `transform_cell`"
2941 "`run_cell_async` will not call `transform_cell`"
2944 " automatically in the future. Please pass the result to"
2942 " automatically in the future. Please pass the result to"
2945 " `transformed_cell` argument and any exception that happen"
2943 " `transformed_cell` argument and any exception that happen"
2946 " during the"
2944 " during the"
2947 "transform in `preprocessing_exc_tuple` in"
2945 "transform in `preprocessing_exc_tuple` in"
2948 " IPython 7.17 and above.",
2946 " IPython 7.17 and above.",
2949 DeprecationWarning,
2947 DeprecationWarning,
2950 stacklevel=2,
2948 stacklevel=2,
2951 )
2949 )
2952 # If any of our input transformation (input_transformer_manager or
2950 # If any of our input transformation (input_transformer_manager or
2953 # prefilter_manager) raises an exception, we store it in this variable
2951 # prefilter_manager) raises an exception, we store it in this variable
2954 # so that we can display the error after logging the input and storing
2952 # so that we can display the error after logging the input and storing
2955 # it in the history.
2953 # it in the history.
2956 try:
2954 try:
2957 cell = self.transform_cell(raw_cell)
2955 cell = self.transform_cell(raw_cell)
2958 except Exception:
2956 except Exception:
2959 preprocessing_exc_tuple = sys.exc_info()
2957 preprocessing_exc_tuple = sys.exc_info()
2960 cell = raw_cell # cell has to exist so it can be stored/logged
2958 cell = raw_cell # cell has to exist so it can be stored/logged
2961 else:
2959 else:
2962 preprocessing_exc_tuple = None
2960 preprocessing_exc_tuple = None
2963 else:
2961 else:
2964 if preprocessing_exc_tuple is None:
2962 if preprocessing_exc_tuple is None:
2965 cell = transformed_cell
2963 cell = transformed_cell
2966 else:
2964 else:
2967 cell = raw_cell
2965 cell = raw_cell
2968
2966
2969 # Store raw and processed history
2967 # Store raw and processed history
2970 if store_history:
2968 if store_history:
2971 self.history_manager.store_inputs(self.execution_count,
2969 self.history_manager.store_inputs(self.execution_count,
2972 cell, raw_cell)
2970 cell, raw_cell)
2973 if not silent:
2971 if not silent:
2974 self.logger.log(cell, raw_cell)
2972 self.logger.log(cell, raw_cell)
2975
2973
2976 # Display the exception if input processing failed.
2974 # Display the exception if input processing failed.
2977 if preprocessing_exc_tuple is not None:
2975 if preprocessing_exc_tuple is not None:
2978 self.showtraceback(preprocessing_exc_tuple)
2976 self.showtraceback(preprocessing_exc_tuple)
2979 if store_history:
2977 if store_history:
2980 self.execution_count += 1
2978 self.execution_count += 1
2981 return error_before_exec(preprocessing_exc_tuple[1])
2979 return error_before_exec(preprocessing_exc_tuple[1])
2982
2980
2983 # Our own compiler remembers the __future__ environment. If we want to
2981 # Our own compiler remembers the __future__ environment. If we want to
2984 # run code with a separate __future__ environment, use the default
2982 # run code with a separate __future__ environment, use the default
2985 # compiler
2983 # compiler
2986 compiler = self.compile if shell_futures else self.compiler_class()
2984 compiler = self.compile if shell_futures else self.compiler_class()
2987
2985
2988 _run_async = False
2986 _run_async = False
2989
2987
2990 with self.builtin_trap:
2988 with self.builtin_trap:
2991 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
2989 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
2992
2990
2993 with self.display_trap:
2991 with self.display_trap:
2994 # Compile to bytecode
2992 # Compile to bytecode
2995 try:
2993 try:
2996 code_ast = compiler.ast_parse(cell, filename=cell_name)
2994 code_ast = compiler.ast_parse(cell, filename=cell_name)
2997 except self.custom_exceptions as e:
2995 except self.custom_exceptions as e:
2998 etype, value, tb = sys.exc_info()
2996 etype, value, tb = sys.exc_info()
2999 self.CustomTB(etype, value, tb)
2997 self.CustomTB(etype, value, tb)
3000 return error_before_exec(e)
2998 return error_before_exec(e)
3001 except IndentationError as e:
2999 except IndentationError as e:
3002 self.showindentationerror()
3000 self.showindentationerror()
3003 return error_before_exec(e)
3001 return error_before_exec(e)
3004 except (OverflowError, SyntaxError, ValueError, TypeError,
3002 except (OverflowError, SyntaxError, ValueError, TypeError,
3005 MemoryError) as e:
3003 MemoryError) as e:
3006 self.showsyntaxerror()
3004 self.showsyntaxerror()
3007 return error_before_exec(e)
3005 return error_before_exec(e)
3008
3006
3009 # Apply AST transformations
3007 # Apply AST transformations
3010 try:
3008 try:
3011 code_ast = self.transform_ast(code_ast)
3009 code_ast = self.transform_ast(code_ast)
3012 except InputRejected as e:
3010 except InputRejected as e:
3013 self.showtraceback()
3011 self.showtraceback()
3014 return error_before_exec(e)
3012 return error_before_exec(e)
3015
3013
3016 # Give the displayhook a reference to our ExecutionResult so it
3014 # Give the displayhook a reference to our ExecutionResult so it
3017 # can fill in the output value.
3015 # can fill in the output value.
3018 self.displayhook.exec_result = result
3016 self.displayhook.exec_result = result
3019
3017
3020 # Execute the user code
3018 # Execute the user code
3021 interactivity = "none" if silent else self.ast_node_interactivity
3019 interactivity = "none" if silent else self.ast_node_interactivity
3022
3020
3023 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3021 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3024 interactivity=interactivity, compiler=compiler, result=result)
3022 interactivity=interactivity, compiler=compiler, result=result)
3025
3023
3026 self.last_execution_succeeded = not has_raised
3024 self.last_execution_succeeded = not has_raised
3027 self.last_execution_result = result
3025 self.last_execution_result = result
3028
3026
3029 # Reset this so later displayed values do not modify the
3027 # Reset this so later displayed values do not modify the
3030 # ExecutionResult
3028 # ExecutionResult
3031 self.displayhook.exec_result = None
3029 self.displayhook.exec_result = None
3032
3030
3033 if store_history:
3031 if store_history:
3034 # Write output to the database. Does nothing unless
3032 # Write output to the database. Does nothing unless
3035 # history output logging is enabled.
3033 # history output logging is enabled.
3036 self.history_manager.store_output(self.execution_count)
3034 self.history_manager.store_output(self.execution_count)
3037 # Each cell is a *single* input, regardless of how many lines it has
3035 # Each cell is a *single* input, regardless of how many lines it has
3038 self.execution_count += 1
3036 self.execution_count += 1
3039
3037
3040 return result
3038 return result
3041
3039
3042 def transform_cell(self, raw_cell):
3040 def transform_cell(self, raw_cell):
3043 """Transform an input cell before parsing it.
3041 """Transform an input cell before parsing it.
3044
3042
3045 Static transformations, implemented in IPython.core.inputtransformer2,
3043 Static transformations, implemented in IPython.core.inputtransformer2,
3046 deal with things like ``%magic`` and ``!system`` commands.
3044 deal with things like ``%magic`` and ``!system`` commands.
3047 These run on all input.
3045 These run on all input.
3048 Dynamic transformations, for things like unescaped magics and the exit
3046 Dynamic transformations, for things like unescaped magics and the exit
3049 autocall, depend on the state of the interpreter.
3047 autocall, depend on the state of the interpreter.
3050 These only apply to single line inputs.
3048 These only apply to single line inputs.
3051
3049
3052 These string-based transformations are followed by AST transformations;
3050 These string-based transformations are followed by AST transformations;
3053 see :meth:`transform_ast`.
3051 see :meth:`transform_ast`.
3054 """
3052 """
3055 # Static input transformations
3053 # Static input transformations
3056 cell = self.input_transformer_manager.transform_cell(raw_cell)
3054 cell = self.input_transformer_manager.transform_cell(raw_cell)
3057
3055
3058 if len(cell.splitlines()) == 1:
3056 if len(cell.splitlines()) == 1:
3059 # Dynamic transformations - only applied for single line commands
3057 # Dynamic transformations - only applied for single line commands
3060 with self.builtin_trap:
3058 with self.builtin_trap:
3061 # use prefilter_lines to handle trailing newlines
3059 # use prefilter_lines to handle trailing newlines
3062 # restore trailing newline for ast.parse
3060 # restore trailing newline for ast.parse
3063 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3061 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3064
3062
3065 lines = cell.splitlines(keepends=True)
3063 lines = cell.splitlines(keepends=True)
3066 for transform in self.input_transformers_post:
3064 for transform in self.input_transformers_post:
3067 lines = transform(lines)
3065 lines = transform(lines)
3068 cell = ''.join(lines)
3066 cell = ''.join(lines)
3069
3067
3070 return cell
3068 return cell
3071
3069
3072 def transform_ast(self, node):
3070 def transform_ast(self, node):
3073 """Apply the AST transformations from self.ast_transformers
3071 """Apply the AST transformations from self.ast_transformers
3074
3072
3075 Parameters
3073 Parameters
3076 ----------
3074 ----------
3077 node : ast.Node
3075 node : ast.Node
3078 The root node to be transformed. Typically called with the ast.Module
3076 The root node to be transformed. Typically called with the ast.Module
3079 produced by parsing user input.
3077 produced by parsing user input.
3080
3078
3081 Returns
3079 Returns
3082 -------
3080 -------
3083 An ast.Node corresponding to the node it was called with. Note that it
3081 An ast.Node corresponding to the node it was called with. Note that it
3084 may also modify the passed object, so don't rely on references to the
3082 may also modify the passed object, so don't rely on references to the
3085 original AST.
3083 original AST.
3086 """
3084 """
3087 for transformer in self.ast_transformers:
3085 for transformer in self.ast_transformers:
3088 try:
3086 try:
3089 node = transformer.visit(node)
3087 node = transformer.visit(node)
3090 except InputRejected:
3088 except InputRejected:
3091 # User-supplied AST transformers can reject an input by raising
3089 # User-supplied AST transformers can reject an input by raising
3092 # an InputRejected. Short-circuit in this case so that we
3090 # an InputRejected. Short-circuit in this case so that we
3093 # don't unregister the transform.
3091 # don't unregister the transform.
3094 raise
3092 raise
3095 except Exception:
3093 except Exception:
3096 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3094 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3097 self.ast_transformers.remove(transformer)
3095 self.ast_transformers.remove(transformer)
3098
3096
3099 if self.ast_transformers:
3097 if self.ast_transformers:
3100 ast.fix_missing_locations(node)
3098 ast.fix_missing_locations(node)
3101 return node
3099 return node
3102
3100
3103 async def run_ast_nodes(
3101 async def run_ast_nodes(
3104 self,
3102 self,
3105 nodelist: ListType[stmt],
3103 nodelist: ListType[stmt],
3106 cell_name: str,
3104 cell_name: str,
3107 interactivity="last_expr",
3105 interactivity="last_expr",
3108 compiler=compile,
3106 compiler=compile,
3109 result=None,
3107 result=None,
3110 ):
3108 ):
3111 """Run a sequence of AST nodes. The execution mode depends on the
3109 """Run a sequence of AST nodes. The execution mode depends on the
3112 interactivity parameter.
3110 interactivity parameter.
3113
3111
3114 Parameters
3112 Parameters
3115 ----------
3113 ----------
3116 nodelist : list
3114 nodelist : list
3117 A sequence of AST nodes to run.
3115 A sequence of AST nodes to run.
3118 cell_name : str
3116 cell_name : str
3119 Will be passed to the compiler as the filename of the cell. Typically
3117 Will be passed to the compiler as the filename of the cell. Typically
3120 the value returned by ip.compile.cache(cell).
3118 the value returned by ip.compile.cache(cell).
3121 interactivity : str
3119 interactivity : str
3122 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3120 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3123 specifying which nodes should be run interactively (displaying output
3121 specifying which nodes should be run interactively (displaying output
3124 from expressions). 'last_expr' will run the last node interactively
3122 from expressions). 'last_expr' will run the last node interactively
3125 only if it is an expression (i.e. expressions in loops or other blocks
3123 only if it is an expression (i.e. expressions in loops or other blocks
3126 are not displayed) 'last_expr_or_assign' will run the last expression
3124 are not displayed) 'last_expr_or_assign' will run the last expression
3127 or the last assignment. Other values for this parameter will raise a
3125 or the last assignment. Other values for this parameter will raise a
3128 ValueError.
3126 ValueError.
3129
3127
3130 compiler : callable
3128 compiler : callable
3131 A function with the same interface as the built-in compile(), to turn
3129 A function with the same interface as the built-in compile(), to turn
3132 the AST nodes into code objects. Default is the built-in compile().
3130 the AST nodes into code objects. Default is the built-in compile().
3133 result : ExecutionResult, optional
3131 result : ExecutionResult, optional
3134 An object to store exceptions that occur during execution.
3132 An object to store exceptions that occur during execution.
3135
3133
3136 Returns
3134 Returns
3137 -------
3135 -------
3138 True if an exception occurred while running code, False if it finished
3136 True if an exception occurred while running code, False if it finished
3139 running.
3137 running.
3140 """
3138 """
3141 if not nodelist:
3139 if not nodelist:
3142 return
3140 return
3143
3141
3144
3142
3145 if interactivity == 'last_expr_or_assign':
3143 if interactivity == 'last_expr_or_assign':
3146 if isinstance(nodelist[-1], _assign_nodes):
3144 if isinstance(nodelist[-1], _assign_nodes):
3147 asg = nodelist[-1]
3145 asg = nodelist[-1]
3148 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3146 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3149 target = asg.targets[0]
3147 target = asg.targets[0]
3150 elif isinstance(asg, _single_targets_nodes):
3148 elif isinstance(asg, _single_targets_nodes):
3151 target = asg.target
3149 target = asg.target
3152 else:
3150 else:
3153 target = None
3151 target = None
3154 if isinstance(target, ast.Name):
3152 if isinstance(target, ast.Name):
3155 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3153 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3156 ast.fix_missing_locations(nnode)
3154 ast.fix_missing_locations(nnode)
3157 nodelist.append(nnode)
3155 nodelist.append(nnode)
3158 interactivity = 'last_expr'
3156 interactivity = 'last_expr'
3159
3157
3160 _async = False
3158 _async = False
3161 if interactivity == 'last_expr':
3159 if interactivity == 'last_expr':
3162 if isinstance(nodelist[-1], ast.Expr):
3160 if isinstance(nodelist[-1], ast.Expr):
3163 interactivity = "last"
3161 interactivity = "last"
3164 else:
3162 else:
3165 interactivity = "none"
3163 interactivity = "none"
3166
3164
3167 if interactivity == 'none':
3165 if interactivity == 'none':
3168 to_run_exec, to_run_interactive = nodelist, []
3166 to_run_exec, to_run_interactive = nodelist, []
3169 elif interactivity == 'last':
3167 elif interactivity == 'last':
3170 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3168 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3171 elif interactivity == 'all':
3169 elif interactivity == 'all':
3172 to_run_exec, to_run_interactive = [], nodelist
3170 to_run_exec, to_run_interactive = [], nodelist
3173 else:
3171 else:
3174 raise ValueError("Interactivity was %r" % interactivity)
3172 raise ValueError("Interactivity was %r" % interactivity)
3175
3173
3176 try:
3174 try:
3177
3175
3178 def compare(code):
3176 def compare(code):
3179 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3177 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3180 return is_async
3178 return is_async
3181
3179
3182 # refactor that to just change the mod constructor.
3180 # refactor that to just change the mod constructor.
3183 to_run = []
3181 to_run = []
3184 for node in to_run_exec:
3182 for node in to_run_exec:
3185 to_run.append((node, "exec"))
3183 to_run.append((node, "exec"))
3186
3184
3187 for node in to_run_interactive:
3185 for node in to_run_interactive:
3188 to_run.append((node, "single"))
3186 to_run.append((node, "single"))
3189
3187
3190 for node, mode in to_run:
3188 for node, mode in to_run:
3191 if mode == "exec":
3189 if mode == "exec":
3192 mod = Module([node], [])
3190 mod = Module([node], [])
3193 elif mode == "single":
3191 elif mode == "single":
3194 mod = ast.Interactive([node])
3192 mod = ast.Interactive([node])
3195 with compiler.extra_flags(
3193 with compiler.extra_flags(
3196 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3194 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3197 if self.autoawait
3195 if self.autoawait
3198 else 0x0
3196 else 0x0
3199 ):
3197 ):
3200 code = compiler(mod, cell_name, mode)
3198 code = compiler(mod, cell_name, mode)
3201 asy = compare(code)
3199 asy = compare(code)
3202 if await self.run_code(code, result, async_=asy):
3200 if await self.run_code(code, result, async_=asy):
3203 return True
3201 return True
3204
3202
3205 # Flush softspace
3203 # Flush softspace
3206 if softspace(sys.stdout, 0):
3204 if softspace(sys.stdout, 0):
3207 print()
3205 print()
3208
3206
3209 except:
3207 except:
3210 # It's possible to have exceptions raised here, typically by
3208 # It's possible to have exceptions raised here, typically by
3211 # compilation of odd code (such as a naked 'return' outside a
3209 # compilation of odd code (such as a naked 'return' outside a
3212 # function) that did parse but isn't valid. Typically the exception
3210 # function) that did parse but isn't valid. Typically the exception
3213 # is a SyntaxError, but it's safest just to catch anything and show
3211 # is a SyntaxError, but it's safest just to catch anything and show
3214 # the user a traceback.
3212 # the user a traceback.
3215
3213
3216 # We do only one try/except outside the loop to minimize the impact
3214 # We do only one try/except outside the loop to minimize the impact
3217 # on runtime, and also because if any node in the node list is
3215 # on runtime, and also because if any node in the node list is
3218 # broken, we should stop execution completely.
3216 # broken, we should stop execution completely.
3219 if result:
3217 if result:
3220 result.error_before_exec = sys.exc_info()[1]
3218 result.error_before_exec = sys.exc_info()[1]
3221 self.showtraceback()
3219 self.showtraceback()
3222 return True
3220 return True
3223
3221
3224 return False
3222 return False
3225
3223
3226 async def run_code(self, code_obj, result=None, *, async_=False):
3224 async def run_code(self, code_obj, result=None, *, async_=False):
3227 """Execute a code object.
3225 """Execute a code object.
3228
3226
3229 When an exception occurs, self.showtraceback() is called to display a
3227 When an exception occurs, self.showtraceback() is called to display a
3230 traceback.
3228 traceback.
3231
3229
3232 Parameters
3230 Parameters
3233 ----------
3231 ----------
3234 code_obj : code object
3232 code_obj : code object
3235 A compiled code object, to be executed
3233 A compiled code object, to be executed
3236 result : ExecutionResult, optional
3234 result : ExecutionResult, optional
3237 An object to store exceptions that occur during execution.
3235 An object to store exceptions that occur during execution.
3238 async_ : Bool (Experimental)
3236 async_ : Bool (Experimental)
3239 Attempt to run top-level asynchronous code in a default loop.
3237 Attempt to run top-level asynchronous code in a default loop.
3240
3238
3241 Returns
3239 Returns
3242 -------
3240 -------
3243 False : successful execution.
3241 False : successful execution.
3244 True : an error occurred.
3242 True : an error occurred.
3245 """
3243 """
3246 # special value to say that anything above is IPython and should be
3244 # special value to say that anything above is IPython and should be
3247 # hidden.
3245 # hidden.
3248 __tracebackhide__ = "__ipython_bottom__"
3246 __tracebackhide__ = "__ipython_bottom__"
3249 # Set our own excepthook in case the user code tries to call it
3247 # Set our own excepthook in case the user code tries to call it
3250 # directly, so that the IPython crash handler doesn't get triggered
3248 # directly, so that the IPython crash handler doesn't get triggered
3251 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3249 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3252
3250
3253 # we save the original sys.excepthook in the instance, in case config
3251 # we save the original sys.excepthook in the instance, in case config
3254 # code (such as magics) needs access to it.
3252 # code (such as magics) needs access to it.
3255 self.sys_excepthook = old_excepthook
3253 self.sys_excepthook = old_excepthook
3256 outflag = True # happens in more places, so it's easier as default
3254 outflag = True # happens in more places, so it's easier as default
3257 try:
3255 try:
3258 try:
3256 try:
3259 self.hooks.pre_run_code_hook()
3257 self.hooks.pre_run_code_hook()
3260 if async_:
3258 if async_:
3261 await eval(code_obj, self.user_global_ns, self.user_ns)
3259 await eval(code_obj, self.user_global_ns, self.user_ns)
3262 else:
3260 else:
3263 exec(code_obj, self.user_global_ns, self.user_ns)
3261 exec(code_obj, self.user_global_ns, self.user_ns)
3264 finally:
3262 finally:
3265 # Reset our crash handler in place
3263 # Reset our crash handler in place
3266 sys.excepthook = old_excepthook
3264 sys.excepthook = old_excepthook
3267 except SystemExit as e:
3265 except SystemExit as e:
3268 if result is not None:
3266 if result is not None:
3269 result.error_in_exec = e
3267 result.error_in_exec = e
3270 self.showtraceback(exception_only=True)
3268 self.showtraceback(exception_only=True)
3271 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3269 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3272 except self.custom_exceptions:
3270 except self.custom_exceptions:
3273 etype, value, tb = sys.exc_info()
3271 etype, value, tb = sys.exc_info()
3274 if result is not None:
3272 if result is not None:
3275 result.error_in_exec = value
3273 result.error_in_exec = value
3276 self.CustomTB(etype, value, tb)
3274 self.CustomTB(etype, value, tb)
3277 except:
3275 except:
3278 if result is not None:
3276 if result is not None:
3279 result.error_in_exec = sys.exc_info()[1]
3277 result.error_in_exec = sys.exc_info()[1]
3280 self.showtraceback(running_compiled_code=True)
3278 self.showtraceback(running_compiled_code=True)
3281 else:
3279 else:
3282 outflag = False
3280 outflag = False
3283 return outflag
3281 return outflag
3284
3282
3285 # For backwards compatibility
3283 # For backwards compatibility
3286 runcode = run_code
3284 runcode = run_code
3287
3285
3288 def check_complete(self, code: str) -> Tuple[str, str]:
3286 def check_complete(self, code: str) -> Tuple[str, str]:
3289 """Return whether a block of code is ready to execute, or should be continued
3287 """Return whether a block of code is ready to execute, or should be continued
3290
3288
3291 Parameters
3289 Parameters
3292 ----------
3290 ----------
3293 source : string
3291 source : string
3294 Python input code, which can be multiline.
3292 Python input code, which can be multiline.
3295
3293
3296 Returns
3294 Returns
3297 -------
3295 -------
3298 status : str
3296 status : str
3299 One of 'complete', 'incomplete', or 'invalid' if source is not a
3297 One of 'complete', 'incomplete', or 'invalid' if source is not a
3300 prefix of valid code.
3298 prefix of valid code.
3301 indent : str
3299 indent : str
3302 When status is 'incomplete', this is some whitespace to insert on
3300 When status is 'incomplete', this is some whitespace to insert on
3303 the next line of the prompt.
3301 the next line of the prompt.
3304 """
3302 """
3305 status, nspaces = self.input_transformer_manager.check_complete(code)
3303 status, nspaces = self.input_transformer_manager.check_complete(code)
3306 return status, ' ' * (nspaces or 0)
3304 return status, ' ' * (nspaces or 0)
3307
3305
3308 #-------------------------------------------------------------------------
3306 #-------------------------------------------------------------------------
3309 # Things related to GUI support and pylab
3307 # Things related to GUI support and pylab
3310 #-------------------------------------------------------------------------
3308 #-------------------------------------------------------------------------
3311
3309
3312 active_eventloop = None
3310 active_eventloop = None
3313
3311
3314 def enable_gui(self, gui=None):
3312 def enable_gui(self, gui=None):
3315 raise NotImplementedError('Implement enable_gui in a subclass')
3313 raise NotImplementedError('Implement enable_gui in a subclass')
3316
3314
3317 def enable_matplotlib(self, gui=None):
3315 def enable_matplotlib(self, gui=None):
3318 """Enable interactive matplotlib and inline figure support.
3316 """Enable interactive matplotlib and inline figure support.
3319
3317
3320 This takes the following steps:
3318 This takes the following steps:
3321
3319
3322 1. select the appropriate eventloop and matplotlib backend
3320 1. select the appropriate eventloop and matplotlib backend
3323 2. set up matplotlib for interactive use with that backend
3321 2. set up matplotlib for interactive use with that backend
3324 3. configure formatters for inline figure display
3322 3. configure formatters for inline figure display
3325 4. enable the selected gui eventloop
3323 4. enable the selected gui eventloop
3326
3324
3327 Parameters
3325 Parameters
3328 ----------
3326 ----------
3329 gui : optional, string
3327 gui : optional, string
3330 If given, dictates the choice of matplotlib GUI backend to use
3328 If given, dictates the choice of matplotlib GUI backend to use
3331 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3329 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3332 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3330 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3333 matplotlib (as dictated by the matplotlib build-time options plus the
3331 matplotlib (as dictated by the matplotlib build-time options plus the
3334 user's matplotlibrc configuration file). Note that not all backends
3332 user's matplotlibrc configuration file). Note that not all backends
3335 make sense in all contexts, for example a terminal ipython can't
3333 make sense in all contexts, for example a terminal ipython can't
3336 display figures inline.
3334 display figures inline.
3337 """
3335 """
3338 from IPython.core import pylabtools as pt
3336 from IPython.core import pylabtools as pt
3339 from matplotlib_inline.backend_inline import configure_inline_support
3337 from matplotlib_inline.backend_inline import configure_inline_support
3340 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3338 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3341
3339
3342 if gui != 'inline':
3340 if gui != 'inline':
3343 # If we have our first gui selection, store it
3341 # If we have our first gui selection, store it
3344 if self.pylab_gui_select is None:
3342 if self.pylab_gui_select is None:
3345 self.pylab_gui_select = gui
3343 self.pylab_gui_select = gui
3346 # Otherwise if they are different
3344 # Otherwise if they are different
3347 elif gui != self.pylab_gui_select:
3345 elif gui != self.pylab_gui_select:
3348 print('Warning: Cannot change to a different GUI toolkit: %s.'
3346 print('Warning: Cannot change to a different GUI toolkit: %s.'
3349 ' Using %s instead.' % (gui, self.pylab_gui_select))
3347 ' Using %s instead.' % (gui, self.pylab_gui_select))
3350 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3348 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3351
3349
3352 pt.activate_matplotlib(backend)
3350 pt.activate_matplotlib(backend)
3353 configure_inline_support(self, backend)
3351 configure_inline_support(self, backend)
3354
3352
3355 # Now we must activate the gui pylab wants to use, and fix %run to take
3353 # Now we must activate the gui pylab wants to use, and fix %run to take
3356 # plot updates into account
3354 # plot updates into account
3357 self.enable_gui(gui)
3355 self.enable_gui(gui)
3358 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3356 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3359 pt.mpl_runner(self.safe_execfile)
3357 pt.mpl_runner(self.safe_execfile)
3360
3358
3361 return gui, backend
3359 return gui, backend
3362
3360
3363 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3361 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3364 """Activate pylab support at runtime.
3362 """Activate pylab support at runtime.
3365
3363
3366 This turns on support for matplotlib, preloads into the interactive
3364 This turns on support for matplotlib, preloads into the interactive
3367 namespace all of numpy and pylab, and configures IPython to correctly
3365 namespace all of numpy and pylab, and configures IPython to correctly
3368 interact with the GUI event loop. The GUI backend to be used can be
3366 interact with the GUI event loop. The GUI backend to be used can be
3369 optionally selected with the optional ``gui`` argument.
3367 optionally selected with the optional ``gui`` argument.
3370
3368
3371 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3369 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3372
3370
3373 Parameters
3371 Parameters
3374 ----------
3372 ----------
3375 gui : optional, string
3373 gui : optional, string
3376 If given, dictates the choice of matplotlib GUI backend to use
3374 If given, dictates the choice of matplotlib GUI backend to use
3377 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3375 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3378 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3376 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3379 matplotlib (as dictated by the matplotlib build-time options plus the
3377 matplotlib (as dictated by the matplotlib build-time options plus the
3380 user's matplotlibrc configuration file). Note that not all backends
3378 user's matplotlibrc configuration file). Note that not all backends
3381 make sense in all contexts, for example a terminal ipython can't
3379 make sense in all contexts, for example a terminal ipython can't
3382 display figures inline.
3380 display figures inline.
3383 import_all : optional, bool, default: True
3381 import_all : optional, bool, default: True
3384 Whether to do `from numpy import *` and `from pylab import *`
3382 Whether to do `from numpy import *` and `from pylab import *`
3385 in addition to module imports.
3383 in addition to module imports.
3386 welcome_message : deprecated
3384 welcome_message : deprecated
3387 This argument is ignored, no welcome message will be displayed.
3385 This argument is ignored, no welcome message will be displayed.
3388 """
3386 """
3389 from IPython.core.pylabtools import import_pylab
3387 from IPython.core.pylabtools import import_pylab
3390
3388
3391 gui, backend = self.enable_matplotlib(gui)
3389 gui, backend = self.enable_matplotlib(gui)
3392
3390
3393 # We want to prevent the loading of pylab to pollute the user's
3391 # We want to prevent the loading of pylab to pollute the user's
3394 # namespace as shown by the %who* magics, so we execute the activation
3392 # namespace as shown by the %who* magics, so we execute the activation
3395 # code in an empty namespace, and we update *both* user_ns and
3393 # code in an empty namespace, and we update *both* user_ns and
3396 # user_ns_hidden with this information.
3394 # user_ns_hidden with this information.
3397 ns = {}
3395 ns = {}
3398 import_pylab(ns, import_all)
3396 import_pylab(ns, import_all)
3399 # warn about clobbered names
3397 # warn about clobbered names
3400 ignored = {"__builtins__"}
3398 ignored = {"__builtins__"}
3401 both = set(ns).intersection(self.user_ns).difference(ignored)
3399 both = set(ns).intersection(self.user_ns).difference(ignored)
3402 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3400 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3403 self.user_ns.update(ns)
3401 self.user_ns.update(ns)
3404 self.user_ns_hidden.update(ns)
3402 self.user_ns_hidden.update(ns)
3405 return gui, backend, clobbered
3403 return gui, backend, clobbered
3406
3404
3407 #-------------------------------------------------------------------------
3405 #-------------------------------------------------------------------------
3408 # Utilities
3406 # Utilities
3409 #-------------------------------------------------------------------------
3407 #-------------------------------------------------------------------------
3410
3408
3411 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3409 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3412 """Expand python variables in a string.
3410 """Expand python variables in a string.
3413
3411
3414 The depth argument indicates how many frames above the caller should
3412 The depth argument indicates how many frames above the caller should
3415 be walked to look for the local namespace where to expand variables.
3413 be walked to look for the local namespace where to expand variables.
3416
3414
3417 The global namespace for expansion is always the user's interactive
3415 The global namespace for expansion is always the user's interactive
3418 namespace.
3416 namespace.
3419 """
3417 """
3420 ns = self.user_ns.copy()
3418 ns = self.user_ns.copy()
3421 try:
3419 try:
3422 frame = sys._getframe(depth+1)
3420 frame = sys._getframe(depth+1)
3423 except ValueError:
3421 except ValueError:
3424 # This is thrown if there aren't that many frames on the stack,
3422 # This is thrown if there aren't that many frames on the stack,
3425 # e.g. if a script called run_line_magic() directly.
3423 # e.g. if a script called run_line_magic() directly.
3426 pass
3424 pass
3427 else:
3425 else:
3428 ns.update(frame.f_locals)
3426 ns.update(frame.f_locals)
3429
3427
3430 try:
3428 try:
3431 # We have to use .vformat() here, because 'self' is a valid and common
3429 # We have to use .vformat() here, because 'self' is a valid and common
3432 # name, and expanding **ns for .format() would make it collide with
3430 # name, and expanding **ns for .format() would make it collide with
3433 # the 'self' argument of the method.
3431 # the 'self' argument of the method.
3434 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3432 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3435 except Exception:
3433 except Exception:
3436 # if formatter couldn't format, just let it go untransformed
3434 # if formatter couldn't format, just let it go untransformed
3437 pass
3435 pass
3438 return cmd
3436 return cmd
3439
3437
3440 def mktempfile(self, data=None, prefix='ipython_edit_'):
3438 def mktempfile(self, data=None, prefix='ipython_edit_'):
3441 """Make a new tempfile and return its filename.
3439 """Make a new tempfile and return its filename.
3442
3440
3443 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3441 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3444 but it registers the created filename internally so ipython cleans it up
3442 but it registers the created filename internally so ipython cleans it up
3445 at exit time.
3443 at exit time.
3446
3444
3447 Optional inputs:
3445 Optional inputs:
3448
3446
3449 - data(None): if data is given, it gets written out to the temp file
3447 - data(None): if data is given, it gets written out to the temp file
3450 immediately, and the file is closed again."""
3448 immediately, and the file is closed again."""
3451
3449
3452 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3450 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3453 self.tempdirs.append(dir_path)
3451 self.tempdirs.append(dir_path)
3454
3452
3455 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3453 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3456 os.close(handle) # On Windows, there can only be one open handle on a file
3454 os.close(handle) # On Windows, there can only be one open handle on a file
3457
3455
3458 file_path = Path(filename)
3456 file_path = Path(filename)
3459 self.tempfiles.append(file_path)
3457 self.tempfiles.append(file_path)
3460
3458
3461 if data:
3459 if data:
3462 file_path.write_text(data)
3460 file_path.write_text(data)
3463 return filename
3461 return filename
3464
3462
3465 def ask_yes_no(self, prompt, default=None, interrupt=None):
3463 def ask_yes_no(self, prompt, default=None, interrupt=None):
3466 if self.quiet:
3464 if self.quiet:
3467 return True
3465 return True
3468 return ask_yes_no(prompt,default,interrupt)
3466 return ask_yes_no(prompt,default,interrupt)
3469
3467
3470 def show_usage(self):
3468 def show_usage(self):
3471 """Show a usage message"""
3469 """Show a usage message"""
3472 page.page(IPython.core.usage.interactive_usage)
3470 page.page(IPython.core.usage.interactive_usage)
3473
3471
3474 def extract_input_lines(self, range_str, raw=False):
3472 def extract_input_lines(self, range_str, raw=False):
3475 """Return as a string a set of input history slices.
3473 """Return as a string a set of input history slices.
3476
3474
3477 Parameters
3475 Parameters
3478 ----------
3476 ----------
3479 range_str : str
3477 range_str : str
3480 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3478 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3481 since this function is for use by magic functions which get their
3479 since this function is for use by magic functions which get their
3482 arguments as strings. The number before the / is the session
3480 arguments as strings. The number before the / is the session
3483 number: ~n goes n back from the current session.
3481 number: ~n goes n back from the current session.
3484
3482
3485 If empty string is given, returns history of current session
3483 If empty string is given, returns history of current session
3486 without the last input.
3484 without the last input.
3487
3485
3488 raw : bool, optional
3486 raw : bool, optional
3489 By default, the processed input is used. If this is true, the raw
3487 By default, the processed input is used. If this is true, the raw
3490 input history is used instead.
3488 input history is used instead.
3491
3489
3492 Notes
3490 Notes
3493 -----
3491 -----
3494
3492
3495 Slices can be described with two notations:
3493 Slices can be described with two notations:
3496
3494
3497 * ``N:M`` -> standard python form, means including items N...(M-1).
3495 * ``N:M`` -> standard python form, means including items N...(M-1).
3498 * ``N-M`` -> include items N..M (closed endpoint).
3496 * ``N-M`` -> include items N..M (closed endpoint).
3499 """
3497 """
3500 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3498 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3501 text = "\n".join(x for _, _, x in lines)
3499 text = "\n".join(x for _, _, x in lines)
3502
3500
3503 # Skip the last line, as it's probably the magic that called this
3501 # Skip the last line, as it's probably the magic that called this
3504 if not range_str:
3502 if not range_str:
3505 if "\n" not in text:
3503 if "\n" not in text:
3506 text = ""
3504 text = ""
3507 else:
3505 else:
3508 text = text[: text.rfind("\n")]
3506 text = text[: text.rfind("\n")]
3509
3507
3510 return text
3508 return text
3511
3509
3512 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3510 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3513 """Get a code string from history, file, url, or a string or macro.
3511 """Get a code string from history, file, url, or a string or macro.
3514
3512
3515 This is mainly used by magic functions.
3513 This is mainly used by magic functions.
3516
3514
3517 Parameters
3515 Parameters
3518 ----------
3516 ----------
3519 target : str
3517 target : str
3520 A string specifying code to retrieve. This will be tried respectively
3518 A string specifying code to retrieve. This will be tried respectively
3521 as: ranges of input history (see %history for syntax), url,
3519 as: ranges of input history (see %history for syntax), url,
3522 corresponding .py file, filename, or an expression evaluating to a
3520 corresponding .py file, filename, or an expression evaluating to a
3523 string or Macro in the user namespace.
3521 string or Macro in the user namespace.
3524
3522
3525 If empty string is given, returns complete history of current
3523 If empty string is given, returns complete history of current
3526 session, without the last line.
3524 session, without the last line.
3527
3525
3528 raw : bool
3526 raw : bool
3529 If true (default), retrieve raw history. Has no effect on the other
3527 If true (default), retrieve raw history. Has no effect on the other
3530 retrieval mechanisms.
3528 retrieval mechanisms.
3531
3529
3532 py_only : bool (default False)
3530 py_only : bool (default False)
3533 Only try to fetch python code, do not try alternative methods to decode file
3531 Only try to fetch python code, do not try alternative methods to decode file
3534 if unicode fails.
3532 if unicode fails.
3535
3533
3536 Returns
3534 Returns
3537 -------
3535 -------
3538 A string of code.
3536 A string of code.
3539
3537
3540 ValueError is raised if nothing is found, and TypeError if it evaluates
3538 ValueError is raised if nothing is found, and TypeError if it evaluates
3541 to an object of another type. In each case, .args[0] is a printable
3539 to an object of another type. In each case, .args[0] is a printable
3542 message.
3540 message.
3543 """
3541 """
3544 code = self.extract_input_lines(target, raw=raw) # Grab history
3542 code = self.extract_input_lines(target, raw=raw) # Grab history
3545 if code:
3543 if code:
3546 return code
3544 return code
3547 try:
3545 try:
3548 if target.startswith(('http://', 'https://')):
3546 if target.startswith(('http://', 'https://')):
3549 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3547 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3550 except UnicodeDecodeError as e:
3548 except UnicodeDecodeError as e:
3551 if not py_only :
3549 if not py_only :
3552 # Deferred import
3550 # Deferred import
3553 from urllib.request import urlopen
3551 from urllib.request import urlopen
3554 response = urlopen(target)
3552 response = urlopen(target)
3555 return response.read().decode('latin1')
3553 return response.read().decode('latin1')
3556 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3554 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3557
3555
3558 potential_target = [target]
3556 potential_target = [target]
3559 try :
3557 try :
3560 potential_target.insert(0,get_py_filename(target))
3558 potential_target.insert(0,get_py_filename(target))
3561 except IOError:
3559 except IOError:
3562 pass
3560 pass
3563
3561
3564 for tgt in potential_target :
3562 for tgt in potential_target :
3565 if os.path.isfile(tgt): # Read file
3563 if os.path.isfile(tgt): # Read file
3566 try :
3564 try :
3567 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3565 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3568 except UnicodeDecodeError as e:
3566 except UnicodeDecodeError as e:
3569 if not py_only :
3567 if not py_only :
3570 with io_open(tgt,'r', encoding='latin1') as f :
3568 with io_open(tgt,'r', encoding='latin1') as f :
3571 return f.read()
3569 return f.read()
3572 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3570 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3573 elif os.path.isdir(os.path.expanduser(tgt)):
3571 elif os.path.isdir(os.path.expanduser(tgt)):
3574 raise ValueError("'%s' is a directory, not a regular file." % target)
3572 raise ValueError("'%s' is a directory, not a regular file." % target)
3575
3573
3576 if search_ns:
3574 if search_ns:
3577 # Inspect namespace to load object source
3575 # Inspect namespace to load object source
3578 object_info = self.object_inspect(target, detail_level=1)
3576 object_info = self.object_inspect(target, detail_level=1)
3579 if object_info['found'] and object_info['source']:
3577 if object_info['found'] and object_info['source']:
3580 return object_info['source']
3578 return object_info['source']
3581
3579
3582 try: # User namespace
3580 try: # User namespace
3583 codeobj = eval(target, self.user_ns)
3581 codeobj = eval(target, self.user_ns)
3584 except Exception as e:
3582 except Exception as e:
3585 raise ValueError(("'%s' was not found in history, as a file, url, "
3583 raise ValueError(("'%s' was not found in history, as a file, url, "
3586 "nor in the user namespace.") % target) from e
3584 "nor in the user namespace.") % target) from e
3587
3585
3588 if isinstance(codeobj, str):
3586 if isinstance(codeobj, str):
3589 return codeobj
3587 return codeobj
3590 elif isinstance(codeobj, Macro):
3588 elif isinstance(codeobj, Macro):
3591 return codeobj.value
3589 return codeobj.value
3592
3590
3593 raise TypeError("%s is neither a string nor a macro." % target,
3591 raise TypeError("%s is neither a string nor a macro." % target,
3594 codeobj)
3592 codeobj)
3595
3593
3596 def _atexit_once(self):
3594 def _atexit_once(self):
3597 """
3595 """
3598 At exist operation that need to be called at most once.
3596 At exist operation that need to be called at most once.
3599 Second call to this function per instance will do nothing.
3597 Second call to this function per instance will do nothing.
3600 """
3598 """
3601
3599
3602 if not getattr(self, "_atexit_once_called", False):
3600 if not getattr(self, "_atexit_once_called", False):
3603 self._atexit_once_called = True
3601 self._atexit_once_called = True
3604 # Clear all user namespaces to release all references cleanly.
3602 # Clear all user namespaces to release all references cleanly.
3605 self.reset(new_session=False)
3603 self.reset(new_session=False)
3606 # Close the history session (this stores the end time and line count)
3604 # Close the history session (this stores the end time and line count)
3607 # this must be *before* the tempfile cleanup, in case of temporary
3605 # this must be *before* the tempfile cleanup, in case of temporary
3608 # history db
3606 # history db
3609 self.history_manager.end_session()
3607 self.history_manager.end_session()
3610 self.history_manager = None
3608 self.history_manager = None
3611
3609
3612 #-------------------------------------------------------------------------
3610 #-------------------------------------------------------------------------
3613 # Things related to IPython exiting
3611 # Things related to IPython exiting
3614 #-------------------------------------------------------------------------
3612 #-------------------------------------------------------------------------
3615 def atexit_operations(self):
3613 def atexit_operations(self):
3616 """This will be executed at the time of exit.
3614 """This will be executed at the time of exit.
3617
3615
3618 Cleanup operations and saving of persistent data that is done
3616 Cleanup operations and saving of persistent data that is done
3619 unconditionally by IPython should be performed here.
3617 unconditionally by IPython should be performed here.
3620
3618
3621 For things that may depend on startup flags or platform specifics (such
3619 For things that may depend on startup flags or platform specifics (such
3622 as having readline or not), register a separate atexit function in the
3620 as having readline or not), register a separate atexit function in the
3623 code that has the appropriate information, rather than trying to
3621 code that has the appropriate information, rather than trying to
3624 clutter
3622 clutter
3625 """
3623 """
3626 self._atexit_once()
3624 self._atexit_once()
3627
3625
3628 # Cleanup all tempfiles and folders left around
3626 # Cleanup all tempfiles and folders left around
3629 for tfile in self.tempfiles:
3627 for tfile in self.tempfiles:
3630 try:
3628 try:
3631 tfile.unlink()
3629 tfile.unlink()
3632 self.tempfiles.remove(tfile)
3630 self.tempfiles.remove(tfile)
3633 except FileNotFoundError:
3631 except FileNotFoundError:
3634 pass
3632 pass
3635 del self.tempfiles
3633 del self.tempfiles
3636 for tdir in self.tempdirs:
3634 for tdir in self.tempdirs:
3637 try:
3635 try:
3638 tdir.rmdir()
3636 tdir.rmdir()
3639 self.tempdirs.remove(tdir)
3637 self.tempdirs.remove(tdir)
3640 except FileNotFoundError:
3638 except FileNotFoundError:
3641 pass
3639 pass
3642 del self.tempdirs
3640 del self.tempdirs
3643
3641
3644
3642
3645 # Run user hooks
3643 # Run user hooks
3646 self.hooks.shutdown_hook()
3644 self.hooks.shutdown_hook()
3647
3645
3648 def cleanup(self):
3646 def cleanup(self):
3649 self.restore_sys_module_state()
3647 self.restore_sys_module_state()
3650
3648
3651
3649
3652 # Overridden in terminal subclass to change prompts
3650 # Overridden in terminal subclass to change prompts
3653 def switch_doctest_mode(self, mode):
3651 def switch_doctest_mode(self, mode):
3654 pass
3652 pass
3655
3653
3656
3654
3657 class InteractiveShellABC(metaclass=abc.ABCMeta):
3655 class InteractiveShellABC(metaclass=abc.ABCMeta):
3658 """An abstract base class for InteractiveShell."""
3656 """An abstract base class for InteractiveShell."""
3659
3657
3660 InteractiveShellABC.register(InteractiveShell)
3658 InteractiveShellABC.register(InteractiveShell)
@@ -1,1052 +1,1048
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 import ast
17 import inspect
17 import inspect
18 from inspect import signature
18 from inspect import signature
19 import linecache
19 import linecache
20 import warnings
20 import warnings
21 import os
21 import os
22 from textwrap import dedent
22 from textwrap import dedent
23 import types
23 import types
24 import io as stdlib_io
24 import io as stdlib_io
25
25
26 from typing import Union
26 from typing import Union
27
27
28 # IPython's own
28 # IPython's own
29 from IPython.core import page
29 from IPython.core import page
30 from IPython.lib.pretty import pretty
30 from IPython.lib.pretty import pretty
31 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest
32 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
33 from IPython.utils import openpy
33 from IPython.utils import openpy
34 from IPython.utils import py3compat
34 from IPython.utils import py3compat
35 from IPython.utils.dir2 import safe_hasattr
35 from IPython.utils.dir2 import safe_hasattr
36 from IPython.utils.path import compress_user
36 from IPython.utils.path import compress_user
37 from IPython.utils.text import indent
37 from IPython.utils.text import indent
38 from IPython.utils.wildcard import list_namespace
38 from IPython.utils.wildcard import list_namespace
39 from IPython.utils.wildcard import typestr2type
39 from IPython.utils.wildcard import typestr2type
40 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
40 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
41 from IPython.utils.py3compat import cast_unicode
41 from IPython.utils.py3compat import cast_unicode
42 from IPython.utils.colorable import Colorable
42 from IPython.utils.colorable import Colorable
43 from IPython.utils.decorators import undoc
43 from IPython.utils.decorators import undoc
44
44
45 from pygments import highlight
45 from pygments import highlight
46 from pygments.lexers import PythonLexer
46 from pygments.lexers import PythonLexer
47 from pygments.formatters import HtmlFormatter
47 from pygments.formatters import HtmlFormatter
48
48
49 def pylight(code):
49 def pylight(code):
50 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
50 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
51
51
52 # builtin docstrings to ignore
52 # builtin docstrings to ignore
53 _func_call_docstring = types.FunctionType.__call__.__doc__
53 _func_call_docstring = types.FunctionType.__call__.__doc__
54 _object_init_docstring = object.__init__.__doc__
54 _object_init_docstring = object.__init__.__doc__
55 _builtin_type_docstrings = {
55 _builtin_type_docstrings = {
56 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
56 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
57 types.FunctionType, property)
57 types.FunctionType, property)
58 }
58 }
59
59
60 _builtin_func_type = type(all)
60 _builtin_func_type = type(all)
61 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
61 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
62 #****************************************************************************
62 #****************************************************************************
63 # Builtin color schemes
63 # Builtin color schemes
64
64
65 Colors = TermColors # just a shorthand
65 Colors = TermColors # just a shorthand
66
66
67 InspectColors = PyColorize.ANSICodeColors
67 InspectColors = PyColorize.ANSICodeColors
68
68
69 #****************************************************************************
69 #****************************************************************************
70 # Auxiliary functions and objects
70 # Auxiliary functions and objects
71
71
72 # See the messaging spec for the definition of all these fields. This list
72 # See the messaging spec for the definition of all these fields. This list
73 # effectively defines the order of display
73 # effectively defines the order of display
74 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
74 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
75 'length', 'file', 'definition', 'docstring', 'source',
75 'length', 'file', 'definition', 'docstring', 'source',
76 'init_definition', 'class_docstring', 'init_docstring',
76 'init_definition', 'class_docstring', 'init_docstring',
77 'call_def', 'call_docstring',
77 'call_def', 'call_docstring',
78 # These won't be printed but will be used to determine how to
78 # These won't be printed but will be used to determine how to
79 # format the object
79 # format the object
80 'ismagic', 'isalias', 'isclass', 'found', 'name'
80 'ismagic', 'isalias', 'isclass', 'found', 'name'
81 ]
81 ]
82
82
83
83
84 def object_info(**kw):
84 def object_info(**kw):
85 """Make an object info dict with all fields present."""
85 """Make an object info dict with all fields present."""
86 infodict = {k:None for k in info_fields}
86 infodict = {k:None for k in info_fields}
87 infodict.update(kw)
87 infodict.update(kw)
88 return infodict
88 return infodict
89
89
90
90
91 def get_encoding(obj):
91 def get_encoding(obj):
92 """Get encoding for python source file defining obj
92 """Get encoding for python source file defining obj
93
93
94 Returns None if obj is not defined in a sourcefile.
94 Returns None if obj is not defined in a sourcefile.
95 """
95 """
96 ofile = find_file(obj)
96 ofile = find_file(obj)
97 # run contents of file through pager starting at line where the object
97 # run contents of file through pager starting at line where the object
98 # is defined, as long as the file isn't binary and is actually on the
98 # is defined, as long as the file isn't binary and is actually on the
99 # filesystem.
99 # filesystem.
100 if ofile is None:
100 if ofile is None:
101 return None
101 return None
102 elif ofile.endswith(('.so', '.dll', '.pyd')):
102 elif ofile.endswith(('.so', '.dll', '.pyd')):
103 return None
103 return None
104 elif not os.path.isfile(ofile):
104 elif not os.path.isfile(ofile):
105 return None
105 return None
106 else:
106 else:
107 # Print only text files, not extension binaries. Note that
107 # Print only text files, not extension binaries. Note that
108 # getsourcelines returns lineno with 1-offset and page() uses
108 # getsourcelines returns lineno with 1-offset and page() uses
109 # 0-offset, so we must adjust.
109 # 0-offset, so we must adjust.
110 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
110 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
111 encoding, lines = openpy.detect_encoding(buffer.readline)
111 encoding, lines = openpy.detect_encoding(buffer.readline)
112 return encoding
112 return encoding
113
113
114 def getdoc(obj) -> Union[str,None]:
114 def getdoc(obj) -> Union[str,None]:
115 """Stable wrapper around inspect.getdoc.
115 """Stable wrapper around inspect.getdoc.
116
116
117 This can't crash because of attribute problems.
117 This can't crash because of attribute problems.
118
118
119 It also attempts to call a getdoc() method on the given object. This
119 It also attempts to call a getdoc() method on the given object. This
120 allows objects which provide their docstrings via non-standard mechanisms
120 allows objects which provide their docstrings via non-standard mechanisms
121 (like Pyro proxies) to still be inspected by ipython's ? system.
121 (like Pyro proxies) to still be inspected by ipython's ? system.
122 """
122 """
123 # Allow objects to offer customized documentation via a getdoc method:
123 # Allow objects to offer customized documentation via a getdoc method:
124 try:
124 try:
125 ds = obj.getdoc()
125 ds = obj.getdoc()
126 except Exception:
126 except Exception:
127 pass
127 pass
128 else:
128 else:
129 if isinstance(ds, str):
129 if isinstance(ds, str):
130 return inspect.cleandoc(ds)
130 return inspect.cleandoc(ds)
131 docstr = inspect.getdoc(obj)
131 docstr = inspect.getdoc(obj)
132 return docstr
132 return docstr
133
133
134
134
135 def getsource(obj, oname='') -> Union[str,None]:
135 def getsource(obj, oname='') -> Union[str,None]:
136 """Wrapper around inspect.getsource.
136 """Wrapper around inspect.getsource.
137
137
138 This can be modified by other projects to provide customized source
138 This can be modified by other projects to provide customized source
139 extraction.
139 extraction.
140
140
141 Parameters
141 Parameters
142 ----------
142 ----------
143 obj : object
143 obj : object
144 an object whose source code we will attempt to extract
144 an object whose source code we will attempt to extract
145 oname : str
145 oname : str
146 (optional) a name under which the object is known
146 (optional) a name under which the object is known
147
147
148 Returns
148 Returns
149 -------
149 -------
150 src : unicode or None
150 src : unicode or None
151
151
152 """
152 """
153
153
154 if isinstance(obj, property):
154 if isinstance(obj, property):
155 sources = []
155 sources = []
156 for attrname in ['fget', 'fset', 'fdel']:
156 for attrname in ['fget', 'fset', 'fdel']:
157 fn = getattr(obj, attrname)
157 fn = getattr(obj, attrname)
158 if fn is not None:
158 if fn is not None:
159 encoding = get_encoding(fn)
159 encoding = get_encoding(fn)
160 oname_prefix = ('%s.' % oname) if oname else ''
160 oname_prefix = ('%s.' % oname) if oname else ''
161 sources.append(''.join(('# ', oname_prefix, attrname)))
161 sources.append(''.join(('# ', oname_prefix, attrname)))
162 if inspect.isfunction(fn):
162 if inspect.isfunction(fn):
163 sources.append(dedent(getsource(fn)))
163 sources.append(dedent(getsource(fn)))
164 else:
164 else:
165 # Default str/repr only prints function name,
165 # Default str/repr only prints function name,
166 # pretty.pretty prints module name too.
166 # pretty.pretty prints module name too.
167 sources.append(
167 sources.append(
168 '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
168 '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
169 )
169 )
170 if sources:
170 if sources:
171 return '\n'.join(sources)
171 return '\n'.join(sources)
172 else:
172 else:
173 return None
173 return None
174
174
175 else:
175 else:
176 # Get source for non-property objects.
176 # Get source for non-property objects.
177
177
178 obj = _get_wrapped(obj)
178 obj = _get_wrapped(obj)
179
179
180 try:
180 try:
181 src = inspect.getsource(obj)
181 src = inspect.getsource(obj)
182 except TypeError:
182 except TypeError:
183 # The object itself provided no meaningful source, try looking for
183 # The object itself provided no meaningful source, try looking for
184 # its class definition instead.
184 # its class definition instead.
185 try:
185 try:
186 src = inspect.getsource(obj.__class__)
186 src = inspect.getsource(obj.__class__)
187 except (OSError, TypeError):
187 except (OSError, TypeError):
188 return None
188 return None
189 except OSError:
189 except OSError:
190 return None
190 return None
191
191
192 return src
192 return src
193
193
194
194
195 def is_simple_callable(obj):
195 def is_simple_callable(obj):
196 """True if obj is a function ()"""
196 """True if obj is a function ()"""
197 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
197 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
198 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
198 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
199
199
200 @undoc
200 @undoc
201 def getargspec(obj):
201 def getargspec(obj):
202 """Wrapper around :func:`inspect.getfullargspec`
202 """Wrapper around :func:`inspect.getfullargspec`
203
203
204 In addition to functions and methods, this can also handle objects with a
204 In addition to functions and methods, this can also handle objects with a
205 ``__call__`` attribute.
205 ``__call__`` attribute.
206
206
207 DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
207 DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
208 """
208 """
209
209
210 warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
210 warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
211 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
211 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
212
212
213 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
213 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
214 obj = obj.__call__
214 obj = obj.__call__
215
215
216 return inspect.getfullargspec(obj)
216 return inspect.getfullargspec(obj)
217
217
218 @undoc
218 @undoc
219 def format_argspec(argspec):
219 def format_argspec(argspec):
220 """Format argspect, convenience wrapper around inspect's.
220 """Format argspect, convenience wrapper around inspect's.
221
221
222 This takes a dict instead of ordered arguments and calls
222 This takes a dict instead of ordered arguments and calls
223 inspect.format_argspec with the arguments in the necessary order.
223 inspect.format_argspec with the arguments in the necessary order.
224
224
225 DEPRECATED (since 7.10): Do not use; will be removed in future versions.
225 DEPRECATED (since 7.10): Do not use; will be removed in future versions.
226 """
226 """
227
227
228 warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
228 warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
229 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
229 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
230
230
231
231
232 return inspect.formatargspec(argspec['args'], argspec['varargs'],
232 return inspect.formatargspec(argspec['args'], argspec['varargs'],
233 argspec['varkw'], argspec['defaults'])
233 argspec['varkw'], argspec['defaults'])
234
234
235 @undoc
235 @undoc
236 def call_tip(oinfo, format_call=True):
236 def call_tip(oinfo, format_call=True):
237 """DEPRECATED since 6.0. Extract call tip data from an oinfo dict."""
237 """DEPRECATED since 6.0. Extract call tip data from an oinfo dict."""
238 warnings.warn(
238 warnings.warn(
239 "`call_tip` function is deprecated as of IPython 6.0"
239 "`call_tip` function is deprecated as of IPython 6.0"
240 "and will be removed in future versions.",
240 "and will be removed in future versions.",
241 DeprecationWarning,
241 DeprecationWarning,
242 stacklevel=2,
242 stacklevel=2,
243 )
243 )
244 # Get call definition
244 # Get call definition
245 argspec = oinfo.get('argspec')
245 argspec = oinfo.get('argspec')
246 if argspec is None:
246 if argspec is None:
247 call_line = None
247 call_line = None
248 else:
248 else:
249 # Callable objects will have 'self' as their first argument, prune
249 # Callable objects will have 'self' as their first argument, prune
250 # it out if it's there for clarity (since users do *not* pass an
250 # it out if it's there for clarity (since users do *not* pass an
251 # extra first argument explicitly).
251 # extra first argument explicitly).
252 try:
252 try:
253 has_self = argspec['args'][0] == 'self'
253 has_self = argspec['args'][0] == 'self'
254 except (KeyError, IndexError):
254 except (KeyError, IndexError):
255 pass
255 pass
256 else:
256 else:
257 if has_self:
257 if has_self:
258 argspec['args'] = argspec['args'][1:]
258 argspec['args'] = argspec['args'][1:]
259
259
260 call_line = oinfo['name']+format_argspec(argspec)
260 call_line = oinfo['name']+format_argspec(argspec)
261
261
262 # Now get docstring.
262 # Now get docstring.
263 # The priority is: call docstring, constructor docstring, main one.
263 # The priority is: call docstring, constructor docstring, main one.
264 doc = oinfo.get('call_docstring')
264 doc = oinfo.get('call_docstring')
265 if doc is None:
265 if doc is None:
266 doc = oinfo.get('init_docstring')
266 doc = oinfo.get('init_docstring')
267 if doc is None:
267 if doc is None:
268 doc = oinfo.get('docstring','')
268 doc = oinfo.get('docstring','')
269
269
270 return call_line, doc
270 return call_line, doc
271
271
272
272
273 def _get_wrapped(obj):
273 def _get_wrapped(obj):
274 """Get the original object if wrapped in one or more @decorators
274 """Get the original object if wrapped in one or more @decorators
275
275
276 Some objects automatically construct similar objects on any unrecognised
276 Some objects automatically construct similar objects on any unrecognised
277 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
277 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
278 this will arbitrarily cut off after 100 levels of obj.__wrapped__
278 this will arbitrarily cut off after 100 levels of obj.__wrapped__
279 attribute access. --TK, Jan 2016
279 attribute access. --TK, Jan 2016
280 """
280 """
281 orig_obj = obj
281 orig_obj = obj
282 i = 0
282 i = 0
283 while safe_hasattr(obj, '__wrapped__'):
283 while safe_hasattr(obj, '__wrapped__'):
284 obj = obj.__wrapped__
284 obj = obj.__wrapped__
285 i += 1
285 i += 1
286 if i > 100:
286 if i > 100:
287 # __wrapped__ is probably a lie, so return the thing we started with
287 # __wrapped__ is probably a lie, so return the thing we started with
288 return orig_obj
288 return orig_obj
289 return obj
289 return obj
290
290
291 def find_file(obj) -> str:
291 def find_file(obj) -> str:
292 """Find the absolute path to the file where an object was defined.
292 """Find the absolute path to the file where an object was defined.
293
293
294 This is essentially a robust wrapper around `inspect.getabsfile`.
294 This is essentially a robust wrapper around `inspect.getabsfile`.
295
295
296 Returns None if no file can be found.
296 Returns None if no file can be found.
297
297
298 Parameters
298 Parameters
299 ----------
299 ----------
300 obj : any Python object
300 obj : any Python object
301
301
302 Returns
302 Returns
303 -------
303 -------
304 fname : str
304 fname : str
305 The absolute path to the file where the object was defined.
305 The absolute path to the file where the object was defined.
306 """
306 """
307 obj = _get_wrapped(obj)
307 obj = _get_wrapped(obj)
308
308
309 fname = None
309 fname = None
310 try:
310 try:
311 fname = inspect.getabsfile(obj)
311 fname = inspect.getabsfile(obj)
312 except TypeError:
312 except TypeError:
313 # For an instance, the file that matters is where its class was
313 # For an instance, the file that matters is where its class was
314 # declared.
314 # declared.
315 try:
315 try:
316 fname = inspect.getabsfile(obj.__class__)
316 fname = inspect.getabsfile(obj.__class__)
317 except (OSError, TypeError):
317 except (OSError, TypeError):
318 # Can happen for builtins
318 # Can happen for builtins
319 pass
319 pass
320 except OSError:
320 except OSError:
321 pass
321 pass
322
322
323 return cast_unicode(fname)
323 return cast_unicode(fname)
324
324
325
325
326 def find_source_lines(obj):
326 def find_source_lines(obj):
327 """Find the line number in a file where an object was defined.
327 """Find the line number in a file where an object was defined.
328
328
329 This is essentially a robust wrapper around `inspect.getsourcelines`.
329 This is essentially a robust wrapper around `inspect.getsourcelines`.
330
330
331 Returns None if no file can be found.
331 Returns None if no file can be found.
332
332
333 Parameters
333 Parameters
334 ----------
334 ----------
335 obj : any Python object
335 obj : any Python object
336
336
337 Returns
337 Returns
338 -------
338 -------
339 lineno : int
339 lineno : int
340 The line number where the object definition starts.
340 The line number where the object definition starts.
341 """
341 """
342 obj = _get_wrapped(obj)
342 obj = _get_wrapped(obj)
343
343
344 try:
344 try:
345 lineno = inspect.getsourcelines(obj)[1]
345 lineno = inspect.getsourcelines(obj)[1]
346 except TypeError:
346 except TypeError:
347 # For instances, try the class object like getsource() does
347 # For instances, try the class object like getsource() does
348 try:
348 try:
349 lineno = inspect.getsourcelines(obj.__class__)[1]
349 lineno = inspect.getsourcelines(obj.__class__)[1]
350 except (OSError, TypeError):
350 except (OSError, TypeError):
351 return None
351 return None
352 except OSError:
352 except OSError:
353 return None
353 return None
354
354
355 return lineno
355 return lineno
356
356
357 class Inspector(Colorable):
357 class Inspector(Colorable):
358
358
359 def __init__(self, color_table=InspectColors,
359 def __init__(self, color_table=InspectColors,
360 code_color_table=PyColorize.ANSICodeColors,
360 code_color_table=PyColorize.ANSICodeColors,
361 scheme=None,
361 scheme=None,
362 str_detail_level=0,
362 str_detail_level=0,
363 parent=None, config=None):
363 parent=None, config=None):
364 super(Inspector, self).__init__(parent=parent, config=config)
364 super(Inspector, self).__init__(parent=parent, config=config)
365 self.color_table = color_table
365 self.color_table = color_table
366 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
366 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
367 self.format = self.parser.format
367 self.format = self.parser.format
368 self.str_detail_level = str_detail_level
368 self.str_detail_level = str_detail_level
369 self.set_active_scheme(scheme)
369 self.set_active_scheme(scheme)
370
370
371 def _getdef(self,obj,oname='') -> Union[str,None]:
371 def _getdef(self,obj,oname='') -> Union[str,None]:
372 """Return the call signature for any callable object.
372 """Return the call signature for any callable object.
373
373
374 If any exception is generated, None is returned instead and the
374 If any exception is generated, None is returned instead and the
375 exception is suppressed."""
375 exception is suppressed."""
376 try:
376 try:
377 return _render_signature(signature(obj), oname)
377 return _render_signature(signature(obj), oname)
378 except:
378 except:
379 return None
379 return None
380
380
381 def __head(self,h) -> str:
381 def __head(self,h) -> str:
382 """Return a header string with proper colors."""
382 """Return a header string with proper colors."""
383 return '%s%s%s' % (self.color_table.active_colors.header,h,
383 return '%s%s%s' % (self.color_table.active_colors.header,h,
384 self.color_table.active_colors.normal)
384 self.color_table.active_colors.normal)
385
385
386 def set_active_scheme(self, scheme):
386 def set_active_scheme(self, scheme):
387 if scheme is not None:
387 if scheme is not None:
388 self.color_table.set_active_scheme(scheme)
388 self.color_table.set_active_scheme(scheme)
389 self.parser.color_table.set_active_scheme(scheme)
389 self.parser.color_table.set_active_scheme(scheme)
390
390
391 def noinfo(self, msg, oname):
391 def noinfo(self, msg, oname):
392 """Generic message when no information is found."""
392 """Generic message when no information is found."""
393 print('No %s found' % msg, end=' ')
393 print('No %s found' % msg, end=' ')
394 if oname:
394 if oname:
395 print('for %s' % oname)
395 print('for %s' % oname)
396 else:
396 else:
397 print()
397 print()
398
398
399 def pdef(self, obj, oname=''):
399 def pdef(self, obj, oname=''):
400 """Print the call signature for any callable object.
400 """Print the call signature for any callable object.
401
401
402 If the object is a class, print the constructor information."""
402 If the object is a class, print the constructor information."""
403
403
404 if not callable(obj):
404 if not callable(obj):
405 print('Object is not callable.')
405 print('Object is not callable.')
406 return
406 return
407
407
408 header = ''
408 header = ''
409
409
410 if inspect.isclass(obj):
410 if inspect.isclass(obj):
411 header = self.__head('Class constructor information:\n')
411 header = self.__head('Class constructor information:\n')
412
412
413
413
414 output = self._getdef(obj,oname)
414 output = self._getdef(obj,oname)
415 if output is None:
415 if output is None:
416 self.noinfo('definition header',oname)
416 self.noinfo('definition header',oname)
417 else:
417 else:
418 print(header,self.format(output), end=' ')
418 print(header,self.format(output), end=' ')
419
419
420 # In Python 3, all classes are new-style, so they all have __init__.
420 # In Python 3, all classes are new-style, so they all have __init__.
421 @skip_doctest
421 @skip_doctest
422 def pdoc(self, obj, oname='', formatter=None):
422 def pdoc(self, obj, oname='', formatter=None):
423 """Print the docstring for any object.
423 """Print the docstring for any object.
424
424
425 Optional:
425 Optional:
426 -formatter: a function to run the docstring through for specially
426 -formatter: a function to run the docstring through for specially
427 formatted docstrings.
427 formatted docstrings.
428
428
429 Examples
429 Examples
430 --------
430 --------
431
432 In [1]: class NoInit:
431 In [1]: class NoInit:
433 ...: pass
432 ...: pass
434
433
435 In [2]: class NoDoc:
434 In [2]: class NoDoc:
436 ...: def __init__(self):
435 ...: def __init__(self):
437 ...: pass
436 ...: pass
438
437
439 In [3]: %pdoc NoDoc
438 In [3]: %pdoc NoDoc
440 No documentation found for NoDoc
439 No documentation found for NoDoc
441
440
442 In [4]: %pdoc NoInit
441 In [4]: %pdoc NoInit
443 No documentation found for NoInit
442 No documentation found for NoInit
444
443
445 In [5]: obj = NoInit()
444 In [5]: obj = NoInit()
446
445
447 In [6]: %pdoc obj
446 In [6]: %pdoc obj
448 No documentation found for obj
447 No documentation found for obj
449
448
450 In [5]: obj2 = NoDoc()
449 In [5]: obj2 = NoDoc()
451
450
452 In [6]: %pdoc obj2
451 In [6]: %pdoc obj2
453 No documentation found for obj2
452 No documentation found for obj2
454 """
453 """
455
454
456 head = self.__head # For convenience
455 head = self.__head # For convenience
457 lines = []
456 lines = []
458 ds = getdoc(obj)
457 ds = getdoc(obj)
459 if formatter:
458 if formatter:
460 ds = formatter(ds).get('plain/text', ds)
459 ds = formatter(ds).get('plain/text', ds)
461 if ds:
460 if ds:
462 lines.append(head("Class docstring:"))
461 lines.append(head("Class docstring:"))
463 lines.append(indent(ds))
462 lines.append(indent(ds))
464 if inspect.isclass(obj) and hasattr(obj, '__init__'):
463 if inspect.isclass(obj) and hasattr(obj, '__init__'):
465 init_ds = getdoc(obj.__init__)
464 init_ds = getdoc(obj.__init__)
466 if init_ds is not None:
465 if init_ds is not None:
467 lines.append(head("Init docstring:"))
466 lines.append(head("Init docstring:"))
468 lines.append(indent(init_ds))
467 lines.append(indent(init_ds))
469 elif hasattr(obj,'__call__'):
468 elif hasattr(obj,'__call__'):
470 call_ds = getdoc(obj.__call__)
469 call_ds = getdoc(obj.__call__)
471 if call_ds:
470 if call_ds:
472 lines.append(head("Call docstring:"))
471 lines.append(head("Call docstring:"))
473 lines.append(indent(call_ds))
472 lines.append(indent(call_ds))
474
473
475 if not lines:
474 if not lines:
476 self.noinfo('documentation',oname)
475 self.noinfo('documentation',oname)
477 else:
476 else:
478 page.page('\n'.join(lines))
477 page.page('\n'.join(lines))
479
478
480 def psource(self, obj, oname=''):
479 def psource(self, obj, oname=''):
481 """Print the source code for an object."""
480 """Print the source code for an object."""
482
481
483 # Flush the source cache because inspect can return out-of-date source
482 # Flush the source cache because inspect can return out-of-date source
484 linecache.checkcache()
483 linecache.checkcache()
485 try:
484 try:
486 src = getsource(obj, oname=oname)
485 src = getsource(obj, oname=oname)
487 except Exception:
486 except Exception:
488 src = None
487 src = None
489
488
490 if src is None:
489 if src is None:
491 self.noinfo('source', oname)
490 self.noinfo('source', oname)
492 else:
491 else:
493 page.page(self.format(src))
492 page.page(self.format(src))
494
493
495 def pfile(self, obj, oname=''):
494 def pfile(self, obj, oname=''):
496 """Show the whole file where an object was defined."""
495 """Show the whole file where an object was defined."""
497
496
498 lineno = find_source_lines(obj)
497 lineno = find_source_lines(obj)
499 if lineno is None:
498 if lineno is None:
500 self.noinfo('file', oname)
499 self.noinfo('file', oname)
501 return
500 return
502
501
503 ofile = find_file(obj)
502 ofile = find_file(obj)
504 # run contents of file through pager starting at line where the object
503 # run contents of file through pager starting at line where the object
505 # is defined, as long as the file isn't binary and is actually on the
504 # is defined, as long as the file isn't binary and is actually on the
506 # filesystem.
505 # filesystem.
507 if ofile.endswith(('.so', '.dll', '.pyd')):
506 if ofile.endswith(('.so', '.dll', '.pyd')):
508 print('File %r is binary, not printing.' % ofile)
507 print('File %r is binary, not printing.' % ofile)
509 elif not os.path.isfile(ofile):
508 elif not os.path.isfile(ofile):
510 print('File %r does not exist, not printing.' % ofile)
509 print('File %r does not exist, not printing.' % ofile)
511 else:
510 else:
512 # Print only text files, not extension binaries. Note that
511 # Print only text files, not extension binaries. Note that
513 # getsourcelines returns lineno with 1-offset and page() uses
512 # getsourcelines returns lineno with 1-offset and page() uses
514 # 0-offset, so we must adjust.
513 # 0-offset, so we must adjust.
515 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
514 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
516
515
517
516
518 def _mime_format(self, text:str, formatter=None) -> dict:
517 def _mime_format(self, text:str, formatter=None) -> dict:
519 """Return a mime bundle representation of the input text.
518 """Return a mime bundle representation of the input text.
520
519
521 - if `formatter` is None, the returned mime bundle has
520 - if `formatter` is None, the returned mime bundle has
522 a `text/plain` field, with the input text.
521 a `text/plain` field, with the input text.
523 a `text/html` field with a `<pre>` tag containing the input text.
522 a `text/html` field with a `<pre>` tag containing the input text.
524
523
525 - if `formatter` is not None, it must be a callable transforming the
524 - if `formatter` is not None, it must be a callable transforming the
526 input text into a mime bundle. Default values for `text/plain` and
525 input text into a mime bundle. Default values for `text/plain` and
527 `text/html` representations are the ones described above.
526 `text/html` representations are the ones described above.
528
527
529 Note:
528 Note:
530
529
531 Formatters returning strings are supported but this behavior is deprecated.
530 Formatters returning strings are supported but this behavior is deprecated.
532
531
533 """
532 """
534 defaults = {
533 defaults = {
535 'text/plain': text,
534 'text/plain': text,
536 'text/html': '<pre>' + text + '</pre>'
535 'text/html': '<pre>' + text + '</pre>'
537 }
536 }
538
537
539 if formatter is None:
538 if formatter is None:
540 return defaults
539 return defaults
541 else:
540 else:
542 formatted = formatter(text)
541 formatted = formatter(text)
543
542
544 if not isinstance(formatted, dict):
543 if not isinstance(formatted, dict):
545 # Handle the deprecated behavior of a formatter returning
544 # Handle the deprecated behavior of a formatter returning
546 # a string instead of a mime bundle.
545 # a string instead of a mime bundle.
547 return {
546 return {
548 'text/plain': formatted,
547 'text/plain': formatted,
549 'text/html': '<pre>' + formatted + '</pre>'
548 'text/html': '<pre>' + formatted + '</pre>'
550 }
549 }
551
550
552 else:
551 else:
553 return dict(defaults, **formatted)
552 return dict(defaults, **formatted)
554
553
555
554
556 def format_mime(self, bundle):
555 def format_mime(self, bundle):
557
556
558 text_plain = bundle['text/plain']
557 text_plain = bundle['text/plain']
559
558
560 text = ''
559 text = ''
561 heads, bodies = list(zip(*text_plain))
560 heads, bodies = list(zip(*text_plain))
562 _len = max(len(h) for h in heads)
561 _len = max(len(h) for h in heads)
563
562
564 for head, body in zip(heads, bodies):
563 for head, body in zip(heads, bodies):
565 body = body.strip('\n')
564 body = body.strip('\n')
566 delim = '\n' if '\n' in body else ' '
565 delim = '\n' if '\n' in body else ' '
567 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
566 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
568
567
569 bundle['text/plain'] = text
568 bundle['text/plain'] = text
570 return bundle
569 return bundle
571
570
572 def _get_info(
571 def _get_info(
573 self, obj, oname="", formatter=None, info=None, detail_level=0, omit_sections=()
572 self, obj, oname="", formatter=None, info=None, detail_level=0, omit_sections=()
574 ):
573 ):
575 """Retrieve an info dict and format it.
574 """Retrieve an info dict and format it.
576
575
577 Parameters
576 Parameters
578 ==========
577 ----------
579
580 obj: any
578 obj : any
581 Object to inspect and return info from
579 Object to inspect and return info from
582 oname: str (default: ''):
580 oname: str (default: ''):
583 Name of the variable pointing to `obj`.
581 Name of the variable pointing to `obj`.
584 formatter: callable
582 formatter : callable
585 info:
583 info:
586 already computed information
584 already computed information
587 detail_level: integer
585 detail_level : integer
588 Granularity of detail level, if set to 1, give more information.
586 Granularity of detail level, if set to 1, give more information.
589 omit_sections: container[str]
587 omit_sections : container[str]
590 Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
588 Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
591 """
589 """
592
590
593 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
591 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
594
592
595 _mime = {
593 _mime = {
596 'text/plain': [],
594 'text/plain': [],
597 'text/html': '',
595 'text/html': '',
598 }
596 }
599
597
600 def append_field(bundle, title:str, key:str, formatter=None):
598 def append_field(bundle, title:str, key:str, formatter=None):
601 if title in omit_sections or key in omit_sections:
599 if title in omit_sections or key in omit_sections:
602 return
600 return
603 field = info[key]
601 field = info[key]
604 if field is not None:
602 if field is not None:
605 formatted_field = self._mime_format(field, formatter)
603 formatted_field = self._mime_format(field, formatter)
606 bundle['text/plain'].append((title, formatted_field['text/plain']))
604 bundle['text/plain'].append((title, formatted_field['text/plain']))
607 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
605 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
608
606
609 def code_formatter(text):
607 def code_formatter(text):
610 return {
608 return {
611 'text/plain': self.format(text),
609 'text/plain': self.format(text),
612 'text/html': pylight(text)
610 'text/html': pylight(text)
613 }
611 }
614
612
615 if info['isalias']:
613 if info['isalias']:
616 append_field(_mime, 'Repr', 'string_form')
614 append_field(_mime, 'Repr', 'string_form')
617
615
618 elif info['ismagic']:
616 elif info['ismagic']:
619 if detail_level > 0:
617 if detail_level > 0:
620 append_field(_mime, 'Source', 'source', code_formatter)
618 append_field(_mime, 'Source', 'source', code_formatter)
621 else:
619 else:
622 append_field(_mime, 'Docstring', 'docstring', formatter)
620 append_field(_mime, 'Docstring', 'docstring', formatter)
623 append_field(_mime, 'File', 'file')
621 append_field(_mime, 'File', 'file')
624
622
625 elif info['isclass'] or is_simple_callable(obj):
623 elif info['isclass'] or is_simple_callable(obj):
626 # Functions, methods, classes
624 # Functions, methods, classes
627 append_field(_mime, 'Signature', 'definition', code_formatter)
625 append_field(_mime, 'Signature', 'definition', code_formatter)
628 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
626 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
629 append_field(_mime, 'Docstring', 'docstring', formatter)
627 append_field(_mime, 'Docstring', 'docstring', formatter)
630 if detail_level > 0 and info['source']:
628 if detail_level > 0 and info['source']:
631 append_field(_mime, 'Source', 'source', code_formatter)
629 append_field(_mime, 'Source', 'source', code_formatter)
632 else:
630 else:
633 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
631 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
634
632
635 append_field(_mime, 'File', 'file')
633 append_field(_mime, 'File', 'file')
636 append_field(_mime, 'Type', 'type_name')
634 append_field(_mime, 'Type', 'type_name')
637 append_field(_mime, 'Subclasses', 'subclasses')
635 append_field(_mime, 'Subclasses', 'subclasses')
638
636
639 else:
637 else:
640 # General Python objects
638 # General Python objects
641 append_field(_mime, 'Signature', 'definition', code_formatter)
639 append_field(_mime, 'Signature', 'definition', code_formatter)
642 append_field(_mime, 'Call signature', 'call_def', code_formatter)
640 append_field(_mime, 'Call signature', 'call_def', code_formatter)
643 append_field(_mime, 'Type', 'type_name')
641 append_field(_mime, 'Type', 'type_name')
644 append_field(_mime, 'String form', 'string_form')
642 append_field(_mime, 'String form', 'string_form')
645
643
646 # Namespace
644 # Namespace
647 if info['namespace'] != 'Interactive':
645 if info['namespace'] != 'Interactive':
648 append_field(_mime, 'Namespace', 'namespace')
646 append_field(_mime, 'Namespace', 'namespace')
649
647
650 append_field(_mime, 'Length', 'length')
648 append_field(_mime, 'Length', 'length')
651 append_field(_mime, 'File', 'file')
649 append_field(_mime, 'File', 'file')
652
650
653 # Source or docstring, depending on detail level and whether
651 # Source or docstring, depending on detail level and whether
654 # source found.
652 # source found.
655 if detail_level > 0 and info['source']:
653 if detail_level > 0 and info['source']:
656 append_field(_mime, 'Source', 'source', code_formatter)
654 append_field(_mime, 'Source', 'source', code_formatter)
657 else:
655 else:
658 append_field(_mime, 'Docstring', 'docstring', formatter)
656 append_field(_mime, 'Docstring', 'docstring', formatter)
659
657
660 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
658 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
661 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
659 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
662 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
660 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
663
661
664
662
665 return self.format_mime(_mime)
663 return self.format_mime(_mime)
666
664
667 def pinfo(
665 def pinfo(
668 self,
666 self,
669 obj,
667 obj,
670 oname="",
668 oname="",
671 formatter=None,
669 formatter=None,
672 info=None,
670 info=None,
673 detail_level=0,
671 detail_level=0,
674 enable_html_pager=True,
672 enable_html_pager=True,
675 omit_sections=(),
673 omit_sections=(),
676 ):
674 ):
677 """Show detailed information about an object.
675 """Show detailed information about an object.
678
676
679 Optional arguments:
677 Optional arguments:
680
678
681 - oname: name of the variable pointing to the object.
679 - oname: name of the variable pointing to the object.
682
680
683 - formatter: callable (optional)
681 - formatter: callable (optional)
684 A special formatter for docstrings.
682 A special formatter for docstrings.
685
683
686 The formatter is a callable that takes a string as an input
684 The formatter is a callable that takes a string as an input
687 and returns either a formatted string or a mime type bundle
685 and returns either a formatted string or a mime type bundle
688 in the form of a dictionary.
686 in the form of a dictionary.
689
687
690 Although the support of custom formatter returning a string
688 Although the support of custom formatter returning a string
691 instead of a mime type bundle is deprecated.
689 instead of a mime type bundle is deprecated.
692
690
693 - info: a structure with some information fields which may have been
691 - info: a structure with some information fields which may have been
694 precomputed already.
692 precomputed already.
695
693
696 - detail_level: if set to 1, more information is given.
694 - detail_level: if set to 1, more information is given.
697
695
698 - omit_sections: set of section keys and titles to omit
696 - omit_sections: set of section keys and titles to omit
699 """
697 """
700 info = self._get_info(
698 info = self._get_info(
701 obj, oname, formatter, info, detail_level, omit_sections=omit_sections
699 obj, oname, formatter, info, detail_level, omit_sections=omit_sections
702 )
700 )
703 if not enable_html_pager:
701 if not enable_html_pager:
704 del info['text/html']
702 del info['text/html']
705 page.page(info)
703 page.page(info)
706
704
707 def info(self, obj, oname="", formatter=None, info=None, detail_level=0):
705 def info(self, obj, oname="", formatter=None, info=None, detail_level=0):
708 """DEPRECATED since 5.0. Compute a dict with detailed information about an object."""
706 """DEPRECATED since 5.0. Compute a dict with detailed information about an object."""
709 if formatter is not None:
707 if formatter is not None:
710 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
708 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
711 'is deprecated as of IPython 5.0 and will have no effects.',
709 'is deprecated as of IPython 5.0 and will have no effects.',
712 DeprecationWarning, stacklevel=2)
710 DeprecationWarning, stacklevel=2)
713 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
711 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
714
712
715 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
713 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
716 """Compute a dict with detailed information about an object.
714 """Compute a dict with detailed information about an object.
717
715
718 Parameters
716 Parameters
719 ==========
717 ----------
720
721 obj: any
718 obj : any
722 An object to find information about
719 An object to find information about
723 oname: str (default: ''):
720 oname : str (default: '')
724 Name of the variable pointing to `obj`.
721 Name of the variable pointing to `obj`.
725 info: (default: None)
722 info : (default: None)
726 A struct (dict like with attr access) with some information fields
723 A struct (dict like with attr access) with some information fields
727 which may have been precomputed already.
724 which may have been precomputed already.
728 detail_level: int (default:0)
725 detail_level : int (default:0)
729 If set to 1, more information is given.
726 If set to 1, more information is given.
730
727
731 Returns
728 Returns
732 =======
729 -------
733
734 An object info dict with known fields from `info_fields`. Keys are
730 An object info dict with known fields from `info_fields`. Keys are
735 strings, values are string or None.
731 strings, values are string or None.
736 """
732 """
737
733
738 if info is None:
734 if info is None:
739 ismagic = False
735 ismagic = False
740 isalias = False
736 isalias = False
741 ospace = ''
737 ospace = ''
742 else:
738 else:
743 ismagic = info.ismagic
739 ismagic = info.ismagic
744 isalias = info.isalias
740 isalias = info.isalias
745 ospace = info.namespace
741 ospace = info.namespace
746
742
747 # Get docstring, special-casing aliases:
743 # Get docstring, special-casing aliases:
748 if isalias:
744 if isalias:
749 if not callable(obj):
745 if not callable(obj):
750 try:
746 try:
751 ds = "Alias to the system command:\n %s" % obj[1]
747 ds = "Alias to the system command:\n %s" % obj[1]
752 except:
748 except:
753 ds = "Alias: " + str(obj)
749 ds = "Alias: " + str(obj)
754 else:
750 else:
755 ds = "Alias to " + str(obj)
751 ds = "Alias to " + str(obj)
756 if obj.__doc__:
752 if obj.__doc__:
757 ds += "\nDocstring:\n" + obj.__doc__
753 ds += "\nDocstring:\n" + obj.__doc__
758 else:
754 else:
759 ds = getdoc(obj)
755 ds = getdoc(obj)
760 if ds is None:
756 if ds is None:
761 ds = '<no docstring>'
757 ds = '<no docstring>'
762
758
763 # store output in a dict, we initialize it here and fill it as we go
759 # store output in a dict, we initialize it here and fill it as we go
764 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
760 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
765
761
766 string_max = 200 # max size of strings to show (snipped if longer)
762 string_max = 200 # max size of strings to show (snipped if longer)
767 shalf = int((string_max - 5) / 2)
763 shalf = int((string_max - 5) / 2)
768
764
769 if ismagic:
765 if ismagic:
770 out['type_name'] = 'Magic function'
766 out['type_name'] = 'Magic function'
771 elif isalias:
767 elif isalias:
772 out['type_name'] = 'System alias'
768 out['type_name'] = 'System alias'
773 else:
769 else:
774 out['type_name'] = type(obj).__name__
770 out['type_name'] = type(obj).__name__
775
771
776 try:
772 try:
777 bclass = obj.__class__
773 bclass = obj.__class__
778 out['base_class'] = str(bclass)
774 out['base_class'] = str(bclass)
779 except:
775 except:
780 pass
776 pass
781
777
782 # String form, but snip if too long in ? form (full in ??)
778 # String form, but snip if too long in ? form (full in ??)
783 if detail_level >= self.str_detail_level:
779 if detail_level >= self.str_detail_level:
784 try:
780 try:
785 ostr = str(obj)
781 ostr = str(obj)
786 str_head = 'string_form'
782 str_head = 'string_form'
787 if not detail_level and len(ostr)>string_max:
783 if not detail_level and len(ostr)>string_max:
788 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
784 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
789 ostr = ("\n" + " " * len(str_head.expandtabs())).\
785 ostr = ("\n" + " " * len(str_head.expandtabs())).\
790 join(q.strip() for q in ostr.split("\n"))
786 join(q.strip() for q in ostr.split("\n"))
791 out[str_head] = ostr
787 out[str_head] = ostr
792 except:
788 except:
793 pass
789 pass
794
790
795 if ospace:
791 if ospace:
796 out['namespace'] = ospace
792 out['namespace'] = ospace
797
793
798 # Length (for strings and lists)
794 # Length (for strings and lists)
799 try:
795 try:
800 out['length'] = str(len(obj))
796 out['length'] = str(len(obj))
801 except Exception:
797 except Exception:
802 pass
798 pass
803
799
804 # Filename where object was defined
800 # Filename where object was defined
805 binary_file = False
801 binary_file = False
806 fname = find_file(obj)
802 fname = find_file(obj)
807 if fname is None:
803 if fname is None:
808 # if anything goes wrong, we don't want to show source, so it's as
804 # if anything goes wrong, we don't want to show source, so it's as
809 # if the file was binary
805 # if the file was binary
810 binary_file = True
806 binary_file = True
811 else:
807 else:
812 if fname.endswith(('.so', '.dll', '.pyd')):
808 if fname.endswith(('.so', '.dll', '.pyd')):
813 binary_file = True
809 binary_file = True
814 elif fname.endswith('<string>'):
810 elif fname.endswith('<string>'):
815 fname = 'Dynamically generated function. No source code available.'
811 fname = 'Dynamically generated function. No source code available.'
816 out['file'] = compress_user(fname)
812 out['file'] = compress_user(fname)
817
813
818 # Original source code for a callable, class or property.
814 # Original source code for a callable, class or property.
819 if detail_level:
815 if detail_level:
820 # Flush the source cache because inspect can return out-of-date
816 # Flush the source cache because inspect can return out-of-date
821 # source
817 # source
822 linecache.checkcache()
818 linecache.checkcache()
823 try:
819 try:
824 if isinstance(obj, property) or not binary_file:
820 if isinstance(obj, property) or not binary_file:
825 src = getsource(obj, oname)
821 src = getsource(obj, oname)
826 if src is not None:
822 if src is not None:
827 src = src.rstrip()
823 src = src.rstrip()
828 out['source'] = src
824 out['source'] = src
829
825
830 except Exception:
826 except Exception:
831 pass
827 pass
832
828
833 # Add docstring only if no source is to be shown (avoid repetitions).
829 # Add docstring only if no source is to be shown (avoid repetitions).
834 if ds and not self._source_contains_docstring(out.get('source'), ds):
830 if ds and not self._source_contains_docstring(out.get('source'), ds):
835 out['docstring'] = ds
831 out['docstring'] = ds
836
832
837 # Constructor docstring for classes
833 # Constructor docstring for classes
838 if inspect.isclass(obj):
834 if inspect.isclass(obj):
839 out['isclass'] = True
835 out['isclass'] = True
840
836
841 # get the init signature:
837 # get the init signature:
842 try:
838 try:
843 init_def = self._getdef(obj, oname)
839 init_def = self._getdef(obj, oname)
844 except AttributeError:
840 except AttributeError:
845 init_def = None
841 init_def = None
846
842
847 # get the __init__ docstring
843 # get the __init__ docstring
848 try:
844 try:
849 obj_init = obj.__init__
845 obj_init = obj.__init__
850 except AttributeError:
846 except AttributeError:
851 init_ds = None
847 init_ds = None
852 else:
848 else:
853 if init_def is None:
849 if init_def is None:
854 # Get signature from init if top-level sig failed.
850 # Get signature from init if top-level sig failed.
855 # Can happen for built-in types (list, etc.).
851 # Can happen for built-in types (list, etc.).
856 try:
852 try:
857 init_def = self._getdef(obj_init, oname)
853 init_def = self._getdef(obj_init, oname)
858 except AttributeError:
854 except AttributeError:
859 pass
855 pass
860 init_ds = getdoc(obj_init)
856 init_ds = getdoc(obj_init)
861 # Skip Python's auto-generated docstrings
857 # Skip Python's auto-generated docstrings
862 if init_ds == _object_init_docstring:
858 if init_ds == _object_init_docstring:
863 init_ds = None
859 init_ds = None
864
860
865 if init_def:
861 if init_def:
866 out['init_definition'] = init_def
862 out['init_definition'] = init_def
867
863
868 if init_ds:
864 if init_ds:
869 out['init_docstring'] = init_ds
865 out['init_docstring'] = init_ds
870
866
871 names = [sub.__name__ for sub in type.__subclasses__(obj)]
867 names = [sub.__name__ for sub in type.__subclasses__(obj)]
872 if len(names) < 10:
868 if len(names) < 10:
873 all_names = ', '.join(names)
869 all_names = ', '.join(names)
874 else:
870 else:
875 all_names = ', '.join(names[:10]+['...'])
871 all_names = ', '.join(names[:10]+['...'])
876 out['subclasses'] = all_names
872 out['subclasses'] = all_names
877 # and class docstring for instances:
873 # and class docstring for instances:
878 else:
874 else:
879 # reconstruct the function definition and print it:
875 # reconstruct the function definition and print it:
880 defln = self._getdef(obj, oname)
876 defln = self._getdef(obj, oname)
881 if defln:
877 if defln:
882 out['definition'] = defln
878 out['definition'] = defln
883
879
884 # First, check whether the instance docstring is identical to the
880 # First, check whether the instance docstring is identical to the
885 # class one, and print it separately if they don't coincide. In
881 # class one, and print it separately if they don't coincide. In
886 # most cases they will, but it's nice to print all the info for
882 # most cases they will, but it's nice to print all the info for
887 # objects which use instance-customized docstrings.
883 # objects which use instance-customized docstrings.
888 if ds:
884 if ds:
889 try:
885 try:
890 cls = getattr(obj,'__class__')
886 cls = getattr(obj,'__class__')
891 except:
887 except:
892 class_ds = None
888 class_ds = None
893 else:
889 else:
894 class_ds = getdoc(cls)
890 class_ds = getdoc(cls)
895 # Skip Python's auto-generated docstrings
891 # Skip Python's auto-generated docstrings
896 if class_ds in _builtin_type_docstrings:
892 if class_ds in _builtin_type_docstrings:
897 class_ds = None
893 class_ds = None
898 if class_ds and ds != class_ds:
894 if class_ds and ds != class_ds:
899 out['class_docstring'] = class_ds
895 out['class_docstring'] = class_ds
900
896
901 # Next, try to show constructor docstrings
897 # Next, try to show constructor docstrings
902 try:
898 try:
903 init_ds = getdoc(obj.__init__)
899 init_ds = getdoc(obj.__init__)
904 # Skip Python's auto-generated docstrings
900 # Skip Python's auto-generated docstrings
905 if init_ds == _object_init_docstring:
901 if init_ds == _object_init_docstring:
906 init_ds = None
902 init_ds = None
907 except AttributeError:
903 except AttributeError:
908 init_ds = None
904 init_ds = None
909 if init_ds:
905 if init_ds:
910 out['init_docstring'] = init_ds
906 out['init_docstring'] = init_ds
911
907
912 # Call form docstring for callable instances
908 # Call form docstring for callable instances
913 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
909 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
914 call_def = self._getdef(obj.__call__, oname)
910 call_def = self._getdef(obj.__call__, oname)
915 if call_def and (call_def != out.get('definition')):
911 if call_def and (call_def != out.get('definition')):
916 # it may never be the case that call def and definition differ,
912 # it may never be the case that call def and definition differ,
917 # but don't include the same signature twice
913 # but don't include the same signature twice
918 out['call_def'] = call_def
914 out['call_def'] = call_def
919 call_ds = getdoc(obj.__call__)
915 call_ds = getdoc(obj.__call__)
920 # Skip Python's auto-generated docstrings
916 # Skip Python's auto-generated docstrings
921 if call_ds == _func_call_docstring:
917 if call_ds == _func_call_docstring:
922 call_ds = None
918 call_ds = None
923 if call_ds:
919 if call_ds:
924 out['call_docstring'] = call_ds
920 out['call_docstring'] = call_ds
925
921
926 return object_info(**out)
922 return object_info(**out)
927
923
928 @staticmethod
924 @staticmethod
929 def _source_contains_docstring(src, doc):
925 def _source_contains_docstring(src, doc):
930 """
926 """
931 Check whether the source *src* contains the docstring *doc*.
927 Check whether the source *src* contains the docstring *doc*.
932
928
933 This is is helper function to skip displaying the docstring if the
929 This is is helper function to skip displaying the docstring if the
934 source already contains it, avoiding repetition of information.
930 source already contains it, avoiding repetition of information.
935 """
931 """
936 try:
932 try:
937 def_node, = ast.parse(dedent(src)).body
933 def_node, = ast.parse(dedent(src)).body
938 return ast.get_docstring(def_node) == doc
934 return ast.get_docstring(def_node) == doc
939 except Exception:
935 except Exception:
940 # The source can become invalid or even non-existent (because it
936 # The source can become invalid or even non-existent (because it
941 # is re-fetched from the source file) so the above code fail in
937 # is re-fetched from the source file) so the above code fail in
942 # arbitrary ways.
938 # arbitrary ways.
943 return False
939 return False
944
940
945 def psearch(self,pattern,ns_table,ns_search=[],
941 def psearch(self,pattern,ns_table,ns_search=[],
946 ignore_case=False,show_all=False, *, list_types=False):
942 ignore_case=False,show_all=False, *, list_types=False):
947 """Search namespaces with wildcards for objects.
943 """Search namespaces with wildcards for objects.
948
944
949 Arguments:
945 Arguments:
950
946
951 - pattern: string containing shell-like wildcards to use in namespace
947 - pattern: string containing shell-like wildcards to use in namespace
952 searches and optionally a type specification to narrow the search to
948 searches and optionally a type specification to narrow the search to
953 objects of that type.
949 objects of that type.
954
950
955 - ns_table: dict of name->namespaces for search.
951 - ns_table: dict of name->namespaces for search.
956
952
957 Optional arguments:
953 Optional arguments:
958
954
959 - ns_search: list of namespace names to include in search.
955 - ns_search: list of namespace names to include in search.
960
956
961 - ignore_case(False): make the search case-insensitive.
957 - ignore_case(False): make the search case-insensitive.
962
958
963 - show_all(False): show all names, including those starting with
959 - show_all(False): show all names, including those starting with
964 underscores.
960 underscores.
965
961
966 - list_types(False): list all available object types for object matching.
962 - list_types(False): list all available object types for object matching.
967 """
963 """
968 #print 'ps pattern:<%r>' % pattern # dbg
964 #print 'ps pattern:<%r>' % pattern # dbg
969
965
970 # defaults
966 # defaults
971 type_pattern = 'all'
967 type_pattern = 'all'
972 filter = ''
968 filter = ''
973
969
974 # list all object types
970 # list all object types
975 if list_types:
971 if list_types:
976 page.page('\n'.join(sorted(typestr2type)))
972 page.page('\n'.join(sorted(typestr2type)))
977 return
973 return
978
974
979 cmds = pattern.split()
975 cmds = pattern.split()
980 len_cmds = len(cmds)
976 len_cmds = len(cmds)
981 if len_cmds == 1:
977 if len_cmds == 1:
982 # Only filter pattern given
978 # Only filter pattern given
983 filter = cmds[0]
979 filter = cmds[0]
984 elif len_cmds == 2:
980 elif len_cmds == 2:
985 # Both filter and type specified
981 # Both filter and type specified
986 filter,type_pattern = cmds
982 filter,type_pattern = cmds
987 else:
983 else:
988 raise ValueError('invalid argument string for psearch: <%s>' %
984 raise ValueError('invalid argument string for psearch: <%s>' %
989 pattern)
985 pattern)
990
986
991 # filter search namespaces
987 # filter search namespaces
992 for name in ns_search:
988 for name in ns_search:
993 if name not in ns_table:
989 if name not in ns_table:
994 raise ValueError('invalid namespace <%s>. Valid names: %s' %
990 raise ValueError('invalid namespace <%s>. Valid names: %s' %
995 (name,ns_table.keys()))
991 (name,ns_table.keys()))
996
992
997 #print 'type_pattern:',type_pattern # dbg
993 #print 'type_pattern:',type_pattern # dbg
998 search_result, namespaces_seen = set(), set()
994 search_result, namespaces_seen = set(), set()
999 for ns_name in ns_search:
995 for ns_name in ns_search:
1000 ns = ns_table[ns_name]
996 ns = ns_table[ns_name]
1001 # Normally, locals and globals are the same, so we just check one.
997 # Normally, locals and globals are the same, so we just check one.
1002 if id(ns) in namespaces_seen:
998 if id(ns) in namespaces_seen:
1003 continue
999 continue
1004 namespaces_seen.add(id(ns))
1000 namespaces_seen.add(id(ns))
1005 tmp_res = list_namespace(ns, type_pattern, filter,
1001 tmp_res = list_namespace(ns, type_pattern, filter,
1006 ignore_case=ignore_case, show_all=show_all)
1002 ignore_case=ignore_case, show_all=show_all)
1007 search_result.update(tmp_res)
1003 search_result.update(tmp_res)
1008
1004
1009 page.page('\n'.join(sorted(search_result)))
1005 page.page('\n'.join(sorted(search_result)))
1010
1006
1011
1007
1012 def _render_signature(obj_signature, obj_name) -> str:
1008 def _render_signature(obj_signature, obj_name) -> str:
1013 """
1009 """
1014 This was mostly taken from inspect.Signature.__str__.
1010 This was mostly taken from inspect.Signature.__str__.
1015 Look there for the comments.
1011 Look there for the comments.
1016 The only change is to add linebreaks when this gets too long.
1012 The only change is to add linebreaks when this gets too long.
1017 """
1013 """
1018 result = []
1014 result = []
1019 pos_only = False
1015 pos_only = False
1020 kw_only = True
1016 kw_only = True
1021 for param in obj_signature.parameters.values():
1017 for param in obj_signature.parameters.values():
1022 if param.kind == inspect._POSITIONAL_ONLY:
1018 if param.kind == inspect._POSITIONAL_ONLY:
1023 pos_only = True
1019 pos_only = True
1024 elif pos_only:
1020 elif pos_only:
1025 result.append('/')
1021 result.append('/')
1026 pos_only = False
1022 pos_only = False
1027
1023
1028 if param.kind == inspect._VAR_POSITIONAL:
1024 if param.kind == inspect._VAR_POSITIONAL:
1029 kw_only = False
1025 kw_only = False
1030 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1026 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1031 result.append('*')
1027 result.append('*')
1032 kw_only = False
1028 kw_only = False
1033
1029
1034 result.append(str(param))
1030 result.append(str(param))
1035
1031
1036 if pos_only:
1032 if pos_only:
1037 result.append('/')
1033 result.append('/')
1038
1034
1039 # add up name, parameters, braces (2), and commas
1035 # add up name, parameters, braces (2), and commas
1040 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1036 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1041 # This doesn’t fit behind “Signature: ” in an inspect window.
1037 # This doesn’t fit behind “Signature: ” in an inspect window.
1042 rendered = '{}(\n{})'.format(obj_name, ''.join(
1038 rendered = '{}(\n{})'.format(obj_name, ''.join(
1043 ' {},\n'.format(r) for r in result)
1039 ' {},\n'.format(r) for r in result)
1044 )
1040 )
1045 else:
1041 else:
1046 rendered = '{}({})'.format(obj_name, ', '.join(result))
1042 rendered = '{}({})'.format(obj_name, ', '.join(result))
1047
1043
1048 if obj_signature.return_annotation is not inspect._empty:
1044 if obj_signature.return_annotation is not inspect._empty:
1049 anno = inspect.formatannotation(obj_signature.return_annotation)
1045 anno = inspect.formatannotation(obj_signature.return_annotation)
1050 rendered += ' -> {}'.format(anno)
1046 rendered += ' -> {}'.format(anno)
1051
1047
1052 return rendered
1048 return rendered
General Comments 0
You need to be logged in to leave comments. Login now