0
# Core Kernel Implementation
1
2
The main IPython kernel that handles code execution, message processing, and maintains kernel state. Provides the core functionality for interactive Python computing including code execution, completion, inspection, debugging, and history management.
3
4
## Capabilities
5
6
### IPython Kernel Class
7
8
Main kernel implementation that processes execution requests and manages kernel state.
9
10
```python { .api }
11
class IPythonKernel:
12
"""
13
Main IPython kernel implementation.
14
15
Handles code execution, completion, introspection, and maintains
16
execution state for interactive Python computing.
17
"""
18
19
def do_execute(self, code, silent=False, store_history=True,
20
user_expressions=None, allow_stdin=None):
21
"""
22
Execute Python code in the kernel.
23
24
Parameters:
25
- code (str): Python code to execute
26
- silent (bool): If True, don't broadcast output
27
- store_history (bool): Whether to store in execution history
28
- user_expressions (dict, optional): Expressions to evaluate
29
- allow_stdin (bool, optional): Whether to allow stdin requests
30
31
Returns:
32
dict: Execution result with status, execution_count, etc.
33
"""
34
35
def do_complete(self, code, cursor_pos):
36
"""
37
Generate code completion suggestions.
38
39
Parameters:
40
- code (str): Code context for completion
41
- cursor_pos (int): Cursor position in code
42
43
Returns:
44
dict: Completion results with matches, cursor positions
45
"""
46
47
def do_inspect(self, code, cursor_pos, detail_level=0):
48
"""
49
Inspect objects and provide documentation.
50
51
Parameters:
52
- code (str): Code containing object to inspect
53
- cursor_pos (int): Cursor position in code
54
- detail_level (int): Level of detail (0=brief, 1=detailed)
55
56
Returns:
57
dict: Inspection results with documentation, source, etc.
58
"""
59
60
def do_history(self, hist_access_type, output, raw, session=None,
61
start=None, stop=None, n=None, pattern=None, unique=False):
62
"""
63
Access execution history.
64
65
Parameters:
66
- hist_access_type (str): Type of history access
67
- output (bool): Include output in results
68
- raw (bool): Return raw input or processed
69
- session (int, optional): Session number
70
- start (int, optional): Start line number
71
- stop (int, optional): Stop line number
72
- n (int, optional): Number of entries
73
- pattern (str, optional): Search pattern
74
- unique (bool): Remove duplicates
75
76
Returns:
77
dict: History entries matching criteria
78
"""
79
80
def do_is_complete(self, code):
81
"""
82
Check if code is complete or needs more input.
83
84
Parameters:
85
- code (str): Code to check for completeness
86
87
Returns:
88
dict: Status indicating complete, incomplete, invalid, or unknown
89
"""
90
91
def do_shutdown(self, restart):
92
"""
93
Shutdown the kernel.
94
95
Parameters:
96
- restart (bool): Whether this is a restart
97
98
Returns:
99
dict: Shutdown confirmation
100
"""
101
102
# Kernel state attributes
103
execution_count: int # Current execution count
104
user_ns: dict # User namespace for code execution
105
shell: object # IPython shell instance
106
```
107
108
### Base Kernel Class
109
110
Foundation kernel class providing core messaging and execution infrastructure.
111
112
```python { .api }
113
class Kernel:
114
"""
115
Base kernel class providing fundamental kernel functionality.
116
117
Implements the Jupyter kernel protocol and provides the framework
118
for message handling and kernel lifecycle management.
119
"""
120
121
def start(self):
122
"""Start the kernel's main event loop."""
123
124
def record_ports(self, ports):
125
"""
126
Record the ports being used by this kernel.
127
128
Parameters:
129
- ports (dict): Dictionary of port names to port numbers
130
"""
131
132
# Protocol version information
133
protocol_version: str
134
protocol_version_info: tuple
135
136
# Kernel identification
137
kernel_info: dict # Kernel metadata and capabilities
138
banner: str # Kernel banner text
139
```
140
141
### Kernel Aliases
142
143
Compatibility aliases for different naming conventions.
144
145
```python { .api }
146
# Backward compatibility alias
147
Kernel = IPythonKernel # Alias for IPythonKernel
148
```
149
150
## Usage Examples
151
152
### Basic Kernel Operations
153
154
```python
155
from ipykernel.ipkernel import IPythonKernel
156
157
# Create kernel instance (typically done by framework)
158
kernel = IPythonKernel()
159
160
# Execute code
161
result = kernel.do_execute("print('Hello, World!')")
162
print(f"Execution count: {result['execution_count']}")
163
print(f"Status: {result['status']}")
164
165
# Get completion suggestions
166
completions = kernel.do_complete("import num", 10)
167
print(f"Matches: {completions['matches']}")
168
169
# Inspect an object
170
inspection = kernel.do_inspect("len", 3, detail_level=1)
171
if inspection['found']:
172
print(f"Documentation: {inspection['data']['text/plain']}")
173
```
174
175
### Code Completeness Checking
176
177
```python
178
from ipykernel.ipkernel import IPythonKernel
179
180
kernel = IPythonKernel()
181
182
# Check if code is complete
183
complete_code = "x = 1"
184
result = kernel.do_is_complete(complete_code)
185
print(f"Status: {result['status']}") # 'complete'
186
187
# Check incomplete code
188
incomplete_code = "if True:"
189
result = kernel.do_is_complete(incomplete_code)
190
print(f"Status: {result['status']}") # 'incomplete'
191
print(f"Indent: {result.get('indent', '')}")
192
```
193
194
### History Access
195
196
```python
197
from ipykernel.ipkernel import IPythonKernel
198
199
kernel = IPythonKernel()
200
201
# Execute some code first
202
kernel.do_execute("x = 42")
203
kernel.do_execute("y = x * 2")
204
205
# Get recent history
206
history = kernel.do_history(
207
hist_access_type='tail',
208
output=True,
209
raw=False,
210
n=5
211
)
212
213
for session, line_num, input_code in history['history']:
214
print(f"[{line_num}]: {input_code}")
215
```
216
217
### Kernel Information
218
219
```python
220
from ipykernel.ipkernel import IPythonKernel
221
222
kernel = IPythonKernel()
223
224
# Get kernel information
225
info = kernel.kernel_info
226
print(f"Language: {info['language_info']['name']}")
227
print(f"Version: {info['language_info']['version']}")
228
print(f"Protocol version: {kernel.protocol_version}")
229
```