Debian Codegraph @

docs/source/development/execution.rst

raw
1 .. _execution_semantics:
2
3 Execution of cells in the IPython kernel
4 ========================================
5
6 When IPython kernel receives `execute_request <https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute>`_
7 with user code, it processes the message in the following phases:
8
9 1. Fire the ``pre_execute`` event.
10 2. Fire the ``pre_run_cell`` event unless silent is ``True``.
11 3. Execute ``run_cell`` method to preprocess ``code``, compile and run it, see below for details.
12 4. If execution succeeds, expressions in ``user_expressions`` are computed.
13 This ensures that any error in the expressions don't affect the main code execution.
14 5. Fire the ``post_execute`` event.
15 6. Fire the ``post_run_cell`` event unless silent is ``True``.
16
17 .. seealso::
18
19 :doc:`/config/callbacks`
20
21
22 Running user ``code``
23 =====================
24
25 First, the ``code`` cell is transformed to expand ``%magic`` and ``!system``
26 commands by ``IPython.core.inputtransformer2``. Then expanded cell is compiled
27 using standard Python :func:`compile` function and executed.
28
29 Python :func:`compile` function provides ``mode`` argument to select one
30 of three ways of compiling code:
31
32 *single*
33 Valid for a single interactive statement (though the source can contain
34 multiple lines, such as a for loop). When compiled in this mode, the
35 generated bytecode contains special instructions that trigger the calling of
36 :func:`sys.displayhook` for any expression in the block that returns a value.
37 This means that a single statement can actually produce multiple calls to
38 :func:`sys.displayhook`, if for example it contains a loop where each
39 iteration computes an unassigned expression would generate 10 calls::
40
41 for i in range(10):
42 i**2
43
44 *exec*
45 An arbitrary amount of source code, this is how modules are compiled.
46 :func:`sys.displayhook` is *never* implicitly called.
47
48 *eval*
49 A single expression that returns a value. :func:`sys.displayhook` is *never*
50 implicitly called.
51
52
53 The ``code`` field is split into individual blocks each of which is valid for
54 execution in 'single' mode, and then:
55
56 - If there is only a single block: it is executed in 'single' mode.
57
58 - If there is more than one block:
59
60 * if the last block is a single line long, run all but the last in 'exec' mode
61 and the very last one in 'single' mode. This makes it easy to type simple
62 expressions at the end to see computed values.
63
64 * if the last block is no more than two lines long, run all but the last in
65 'exec' mode and the very last one in 'single' mode. This makes it easy to
66 type simple expressions at the end to see computed values. - otherwise
67 (last one is also multiline), run all in 'exec' mode
68
69 * otherwise (last block is also multiline), run all in 'exec' mode as a single
70 unit.
71
72