Important
This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.
If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).
Execution of cells in the IPython kernel¶
When IPython kernel receives execute_request with user code, it processes the message in the following phases:
Fire the
pre_execute
event.Fire the
pre_run_cell
event unless silent isTrue
.Execute
run_cell
method to preprocesscode
, compile and run it, see below for details.If execution succeeds, expressions in
user_expressions
are computed. This ensures that any error in the expressions don’t affect the main code execution.Fire the
post_execute
event.Fire the
post_run_cell
event unless silent isTrue
.
See also
Running user code
¶
First, the code
cell is transformed to expand %magic
and !system
commands by IPython.core.inputtransformer2
. Then expanded cell is compiled
using standard Python compile()
function and executed.
Python compile()
function provides mode
argument to select one
of three ways of compiling code:
- single
Valid for a single interactive statement (though the source can contain multiple lines, such as a for loop). When compiled in this mode, the generated bytecode contains special instructions that trigger the calling of
sys.displayhook()
for any expression in the block that returns a value. This means that a single statement can actually produce multiple calls tosys.displayhook()
, if for example it contains a loop where each iteration computes an unassigned expression would generate 10 calls:for i in range(10): i**2
- exec
An arbitrary amount of source code, this is how modules are compiled.
sys.displayhook()
is never implicitly called.- eval
A single expression that returns a value.
sys.displayhook()
is never implicitly called.
The code
field is split into individual blocks each of which is valid for
execution in ‘single’ mode, and then:
If there is only a single block: it is executed in ‘single’ mode.
If there is more than one block:
if the last block is a single line long, run all but the last in ‘exec’ mode and the very last one in ‘single’ mode. This makes it easy to type simple expressions at the end to see computed values.
if the last block is no more than two lines long, run all but the last in ‘exec’ mode and the very last one in ‘single’ mode. This makes it easy to type simple expressions at the end to see computed values. - otherwise (last one is also multiline), run all in ‘exec’ mode
otherwise (last block is also multiline), run all in ‘exec’ mode as a single unit.