### Install and Configure Pre-commit Hooks Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md Install the pre-commit package and set up the git hooks for automatic code formatting. Run `pre-commit install` to enable the hooks. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install ipykernel for Development Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md Clone the repository and perform a development installation using pip. ```bash git clone https://github.com/ipython/ipykernel cd ipykernel pip install -e . ``` -------------------------------- ### Install IPython Kernel using Command Line Source: https://context7.com/ipython/ipykernel/llms.txt Installs the IPython kernel via the command line. Options include user installation, custom names, display names, specific prefixes for virtual environments, environment variables, and IPython profiles. ```bash # Install for current user python -m ipykernel install --user # Install with custom name and display name python -m ipykernel install --user --name myenv --display-name "Python (myenv)" # Install to a specific prefix (conda/virtualenv) python -m ipykernel install --prefix=/path/to/env --name conda_env # Install with environment variables python -m ipykernel install --user --name mykernel --env MY_VAR my_value # Install with IPython profile python -m ipykernel install --user --name data_kernel --profile data_science ``` -------------------------------- ### Install IPython Kernel using Python Source: https://context7.com/ipython/ipykernel/llms.txt Installs the IPython kernel for Jupyter. Use `user=True` for current user installation. Custom names, display names, prefixes, and environment variables can be specified. ```python from ipykernel.kernelspec import install # Install kernel for current user dest = install(user=True) print(f"Installed kernel at: {dest}") # Install kernel with custom name for a virtual environment dest = install( kernel_name="my_env_python", display_name="Python (my_env)", prefix="/path/to/virtualenv", env={"MY_VAR": "value"} ) # Install with IPython profile dest = install( kernel_name="python_data", profile="data_science", user=True ) ``` -------------------------------- ### Manage Kernel Connection Files Source: https://context7.com/ipython/ipykernel/llms.txt Work with kernel connection files to connect clients to running kernels. This includes getting the current connection file, retrieving connection information, connecting a Qt console, and writing custom connection files. ```python from ipykernel.connect import ( get_connection_file, get_connection_info, connect_qtconsole, write_connection_file ) # Get the connection file path of the current kernel try: cf = get_connection_file() print(f"Connection file: {cf}") except RuntimeError: print("Not running inside a kernel") # Read connection info as a dict try: info = get_connection_info(unpack=True) print(f"Shell port: {info['shell_port']}") print(f"IOPub port: {info['iopub_port']}") print(f"Stdin port: {info['stdin_port']}") print(f"Control port: {info['control_port']}") print(f"HB port: {info['hb_port']}") except RuntimeError: pass # Connect a Qt console to the running kernel try: proc = connect_qtconsole() print(f"Qt console started with PID: {proc.pid}") except RuntimeError: pass # Write a custom connection file write_connection_file( fname='/tmp/my_kernel.json', ip='127.0.0.1', shell_port=5555, iopub_port=5556, stdin_port=5557, control_port=5558, hb_port=5559, key=b'my-secret-key' ) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/ipython/ipykernel/blob/main/README.md Execute tests using pytest. Ensure you have followed the source installation instructions first. ```bash pytest ``` -------------------------------- ### Launch IPython Kernel Programmatically Source: https://context7.com/ipython/ipykernel/llms.txt Launches an IPython kernel from Python code using `IPKernelApp`. Supports configuration options like matplotlib integration and stderr redirection. Accesses connection details and starts the kernel. ```python from ipykernel.kernelapp import IPKernelApp # Create and initialize the kernel application app = IPKernelApp.instance() app.initialize([ '--matplotlib=inline', # Enable inline matplotlib '--no-stderr', # Optionally redirect stderr ]) # Access connection information print(f"Connection file: {app.abs_connection_file}") print(f"Shell port: {app.shell_port}") print(f"IOPub port: {app.iopub_port}") # Start the kernel (blocks until shutdown) app.start() ``` -------------------------------- ### History Access: Range Request Source: https://context7.com/ipython/ipykernel/llms.txt Request to retrieve a specific range of entries from the kernel's execution history. Allows specifying session, start, and stop points, and whether to include output. ```python history_range = { 'content': { 'output': True, # Include output 'raw': False, # Get transformed code 'hist_access_type': 'range', 'session': 0, # Current session 'start': 1, 'stop': 10, } } ``` -------------------------------- ### Manual Release Steps Source: https://github.com/ipython/ipykernel/blob/main/RELEASE.md Use these commands for a manual release. Ensure you have updated the CHANGELOG and set the VERSION environment variable before running. ```bash export VERSION= pip install pipx pipx run hatch version $VERSION git commit -a -m "Release $VERSION" git tag $VERSION; true; git push --all git push --tags rm -rf dist build pipx run build . pipx run twine check dist/* pipx run twine upload dist/* ``` -------------------------------- ### Release ipykernel - Prepare and Tag Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md Set the version in `_version.py`, commit the change, and create a git tag for the release. Ensure the version is correctly updated before proceeding. ```bash VERSION="4.9.0" git add ipykernel/_version.py git commit -m "release $VERSION" git tag -am "release $VERSION" $VERSION git push git push --tags ``` -------------------------------- ### Release ipykernel - Build and Upload Wheels Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md Build source distribution and wheels for Python 3, and a separate wheel for Python 2 if applicable (for 4.x branch). Upload the distribution files to PyPI using twine. ```bash pip install --upgrade twine git clean -xfd python3 setup.py sdist bdist_wheel python2 setup.py bdist_wheel twine upload dist/* ``` -------------------------------- ### Use Comms for Frontend-Kernel Communication Source: https://context7.com/ipython/ipykernel/llms.txt Create custom communication channels between the kernel and frontends using the `comm` library. This involves creating a comm, opening it with initial data, sending messages, registering handlers for incoming messages, and closing the comm. ```python from comm import create_comm # Create a comm targeting a frontend widget comm = create_comm(target_name='my_widget') # Open the comm with initial data comm.open(data={'initial': 'state'}) # Send data to the frontend comm.send(data={'update': 'new_value', 'count': 42}) # Register a handler for incoming messages def handle_msg(msg): data = msg['content']['data'] print(f"Received from frontend: {data}") # Respond back comm.send(data={'response': 'acknowledged'}) comm.on_msg(handle_msg) # Close the comm when done comm.close(data={'reason': 'finished'}) ``` -------------------------------- ### Run Pre-commit Hooks Manually Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md Manually invoke the pre-commit hooks to format code and check for errors. Use `--all-files` to format the entire repository. ```bash pre-commit run ``` ```bash pre-commit run --all-files ``` -------------------------------- ### Embed IPython Kernel in GUI Applications Source: https://context7.com/ipython/ipykernel/llms.txt A helper class pattern for embedding an IPython kernel within GUI frameworks like Qt, Tk, or wxPython. Initializes the kernel with a specified matplotlib backend and provides methods to manage the kernel and connect consoles. ```python from ipykernel.kernelapp import IPKernelApp from ipykernel.connect import connect_qtconsole class InternalIPKernel: """Helper class to embed IPython kernel in GUI applications.""" def __init__(self): self.ipkernel = None self.consoles = [] self.namespace = {} def init_ipkernel(self, backend='qt'): """Initialize the kernel with matplotlib backend. Parameters ---------- backend : str Matplotlib backend ('qt', 'tk', 'wx', 'gtk', 'inline') """ self.ipkernel = IPKernelApp.instance() self.ipkernel.initialize([ 'python', f'--matplotlib={backend}', ]) # Get reference to user namespace self.namespace = self.ipkernel.shell.user_ns # Add application variables to namespace self.namespace['app'] = self self.namespace['kernel'] = self.ipkernel def new_console(self): """Open a new Qt console connected to this kernel.""" console = connect_qtconsole( self.ipkernel.abs_connection_file ) self.consoles.append(console) return console def start(self): """Start the kernel event loop.""" self.ipkernel.start() def cleanup(self): """Clean up consoles and resources.""" for console in self.consoles: console.kill() self.consoles.clear() # Usage: # kernel = InternalIPKernel() # kernel.init_ipkernel('qt') # kernel.namespace['my_data'] = [1, 2, 3] # kernel.new_console() # kernel.start() ``` -------------------------------- ### Create a Custom IPython Kernel Class Source: https://context7.com/ipython/ipykernel/llms.txt Extend IPythonKernel to create custom kernels with modified behavior, such as adding custom configuration options or overriding execution logic. Use IPKernelApp to instantiate your custom kernel. ```python from ipykernel.ipkernel import IPythonKernel from traitlets import Unicode, Bool class MyCustomKernel(IPythonKernel): """A custom IPython kernel with additional features.""" implementation = 'my_custom_kernel' implementation_version = '1.0' # Add custom configuration custom_greeting = Unicode("Welcome!", config=True) enable_logging = Bool(False, config=True) def __init__(self, **kwargs): super().__init__(**kwargs) if self.shell: # Add custom variable to user namespace self.shell.user_ns['greeting'] = self.custom_greeting async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_meta=None, cell_id=None): """Override execute to add custom logging.""" if self.enable_logging: self.log.info(f"Executing: {code[:50]}...") # Call parent implementation return await super().do_execute( code, silent, store_history, user_expressions, allow_stdin, cell_meta=cell_meta, cell_id=cell_id ) # To use with IPKernelApp: # app = IPKernelApp.instance(kernel_class=MyCustomKernel) ``` -------------------------------- ### Release ipykernel - Reset to Development Version Source: https://github.com/ipython/ipykernel/blob/main/CONTRIBUTING.md After uploading the release, update the version in `_version.py` back to a development version (e.g., '.dev') and commit the change. ```bash git add ipykernel/_version.py git commit -m "back to dev" git push ``` -------------------------------- ### Access Kernel Information and Protocol Details Source: https://context7.com/ipython/ipykernel/llms.txt Query kernel information and protocol details programmatically using attributes from the `ipykernel` package. This includes accessing the kernel version, version info tuple, and kernel protocol version. ```python from ipykernel import __version__, kernel_protocol_version, version_info from ipykernel.ipkernel import IPythonKernel # Get version information print(f"ipykernel version: {__version__}") print(f"Version info tuple: {version_info}") print(f"Kernel protocol version: {kernel_protocol_version}") # Get kernel info dict (as would be sent to frontends) class KernelInfo: @staticmethod def get_kernel_info(): """Get the kernel info that would be returned to clients.""" return { 'protocol_version': kernel_protocol_version, 'implementation': 'ipython', 'implementation_version': __version__, 'language_info': { 'name': 'python', 'version': '3.10.0', # sys.version.split()[0] 'mimetype': 'text/x-python', 'file_extension': '.py', }, 'banner': 'IPython Kernel', } info = KernelInfo.get_kernel_info() print(f"Protocol: {info['protocol_version']}") print(f"Language: {info['language_info']['name']}") ``` -------------------------------- ### IPython Copyright and License Banner Source: https://github.com/ipython/ipykernel/blob/main/README.md Standard banner to be included in source code files indicating copyright and license terms. ```python # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. ``` -------------------------------- ### IPykernel Usage Metrics Request and Reply Source: https://context7.com/ipython/ipykernel/llms.txt Defines the message structure for requesting and receiving kernel resource usage information, including CPU, memory, and host system metrics. ```python # Usage request (sent on control channel) usage_request = { 'header': {'msg_type': 'usage_request'}, 'content': {} } # Usage reply with system metrics usage_reply = { 'hostname': 'my-machine', 'pid': 12345, 'kernel_cpu': 15.5, # CPU percent used by kernel 'kernel_memory': 104857600, # Memory in bytes (PSS or RSS) 'host_cpu_percent': 35.2, # Total host CPU usage 'cpu_count': 8, # Logical CPU count 'host_virtual_memory': { 'total': 17179869184, 'available': 8589934592, 'percent': 50.0, 'used': 8589934592, 'free': 8589934592, } } ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/ipython/ipykernel/blob/main/README.md Execute tests with coverage reporting using pytest. This command provides detailed coverage information. ```bash pytest -vv -s --cov ipykernel --cov-branch --cov-report term-missing:skip-covered --durations 10 ``` -------------------------------- ### Execution Request and Reply Source: https://context7.com/ipython/ipykernel/llms.txt Details the structure of messages for executing code and the kernel's reply. ```APIDOC ## Execute Request and Reply ### Description This section describes the message structure for executing code and the corresponding reply from the kernel. ### Method N/A (Message-based communication) ### Endpoint N/A (Message-based communication) ### Request Body (execute_request) - **header** (dict) - Contains message type, ID, and session information. - **msg_type** (string) - Must be 'execute_request'. - **msg_id** (string) - Unique identifier for the message. - **session** (string) - Identifier for the session. - **content** (dict) - Contains the code to execute and execution options. - **code** (string) - The code to be executed. - **silent** (boolean) - If True, suppresses output. - **store_history** (boolean) - If True, stores the code in history. - **user_expressions** (dict) - Expressions to evaluate. - **allow_stdin** (boolean) - If True, allows standard input. - **stop_on_error** (boolean) - If True, stops execution on error. - **metadata** (dict) - Optional metadata. - **cellId** (string) - Optional cell identifier. ### Response (execute_reply) - **header** (dict) - Contains message type. - **msg_type** (string) - Will be 'execute_reply'. - **content** (dict) - Contains the execution status and results. - **status** (string) - 'ok' or 'error'. - **execution_count** (integer) - The execution count of the cell. - **ename** (string) - (On error) The exception name. - **evalue** (string) - (On error) The exception value. - **traceback** (list) - (On error) A list of traceback strings. ### Response Example (stream_msg) - **header** (dict) - Contains message type. - **msg_type** (string) - Will be 'stream'. - **content** (dict) - Contains stream output. - **name** (string) - 'stdout' or 'stderr'. - **text** (string) - The output text. ``` -------------------------------- ### Code Completion Reply Format Source: https://context7.com/ipython/ipykernel/llms.txt The reply from the kernel for a code completion request. Includes a list of matching suggestions, cursor positions, and optional metadata. ```python complete_reply = { 'status': 'ok', 'matches': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'], 'cursor_start': 17, # Start of text being completed 'cursor_end': 21, # End of text being completed 'metadata': { # Experimental completion metadata with types '_jupyter_types_experimental': [ {'text': 'isabs', 'type': 'function', 'signature': '(s)'}, {'text': 'isdir', 'type': 'function', 'signature': '(s)'}, ] } } ``` -------------------------------- ### IPykernel 7+ Subshell Communication Patterns Source: https://context7.com/ipython/ipykernel/llms.txt Illustrates the message structure for managing subshells in IPykernel 7+, including requests to create, execute within, list, and delete subshells. ```python # Subshell requests are handled on the control channel # Create a new subshell create_subshell_request = { 'header': {'msg_type': 'create_subshell_request'}, 'content': {} } create_subshell_reply = { 'status': 'ok', 'subshell_id': 'uuid-of-new-subshell' } # Execute in specific subshell by adding subshell_id to header execute_in_subshell = { 'header': { 'msg_type': 'execute_request', 'subshell_id': 'uuid-of-subshell', # Target specific subshell }, 'content': { 'code': 'long_running_task()', 'silent': False, } } # List active subshells list_subshell_request = { 'header': {'msg_type': 'list_subshell_request'}, 'content': {} } list_subshell_reply = { 'status': 'ok', 'subshell_ids': ['uuid-1', 'uuid-2'] } # Delete a subshell delete_subshell_request = { 'header': {'msg_type': 'delete_subshell_request'}, 'content': {'subshell_id': 'uuid-to-delete'} } ``` -------------------------------- ### In-Process Kernel for GUI Applications Source: https://context7.com/ipython/ipykernel/llms.txt Utilizes an in-process kernel for tight integration in GUI applications, avoiding IPC overhead. Manages kernel lifecycle, client connections, code execution, and output processing. ```python from ipykernel.inprocess import InProcessKernelManager # Create kernel manager km = InProcessKernelManager() km.start_kernel() # Get a client to interact with the kernel client = km.client() client.start_channels() # Execute code msg_id = client.execute("x = 42") reply = client.get_shell_msg(timeout=5) print(f"Execution status: {reply['content']['status']}") # Execute more code and get output msg_id = client.execute("print(x * 2)") # Process IOPub messages to see output while True: try: msg = client.get_iopub_msg(timeout=1) if msg['msg_type'] == 'stream': print(f"Output: {msg['content']['text']}") elif msg['msg_type'] == 'status' and msg['content']['execution_state'] == 'idle': break except: break # Cleanup client.stop_channels() km.shutdown_kernel() ``` -------------------------------- ### History Access: Search Request Source: https://context7.com/ipython/ipykernel/llms.txt Request to search the kernel's execution history based on a pattern. Can specify the number of results and whether to return unique entries. ```python history_search = { 'content': { 'output': False, 'raw': True, 'hist_access_type': 'search', 'pattern': 'import*', 'n': 100, 'unique': True, } } ``` -------------------------------- ### Code Completion Request Format Source: https://context7.com/ipython/ipykernel/llms.txt Represents a code completion request sent to the kernel. Specifies the code and the cursor position for context. ```python complete_request = { 'content': { 'code': 'import os\nos.path.is', 'cursor_pos': 21, # Position after 'is' } } ``` -------------------------------- ### Handle Kernel Shutdown and Interrupts Source: https://context7.com/ipython/ipykernel/llms.txt Implement custom logic for kernel shutdown and interrupt events by subclassing Kernel. Ensure resources are cleaned up and state is saved. ```python from ipykernel.kernelbase import Kernel class MyKernel(Kernel): """Example showing interrupt and shutdown handling.""" def do_shutdown(self, restart): """Handle kernel shutdown request. Parameters ---------- restart : bool Whether the kernel will be restarted after shutdown. Returns ------- dict Shutdown reply content. """ # Cleanup resources self.log.info("Shutting down kernel...") # Close any open connections # Save any necessary state if restart: self.log.info("Kernel will restart") return {'status': 'ok', 'restart': restart} def do_is_complete(self, code): """Check if code is complete and ready to execute. Returns ------- dict Status can be 'complete', 'incomplete', 'invalid', or 'unknown'. """ # Simple check - real implementation uses IPython's parser if code.strip().endswith(':'): return {'status': 'incomplete', 'indent': ' '} elif code.count('(') != code.count(')'): return {'status': 'incomplete', 'indent': ''} else: return {'status': 'complete'} ``` -------------------------------- ### Code Completion API Source: https://context7.com/ipython/ipykernel/llms.txt API for retrieving code completion suggestions based on the current code and cursor position. ```APIDOC ## Code Completion API ### Description Provides code completion suggestions based on the current code and cursor position. This API is handled by the `do_complete` method of the kernel. ### Method N/A (Message-based communication) ### Endpoint N/A (Message-based communication) ### Request Body (complete_request) - **content** (dict) - **code** (string) - The code string to analyze for completions. - **cursor_pos** (integer) - The cursor's position within the code string. ### Response (complete_reply) - **status** (string) - 'ok' indicating success. - **matches** (list) - A list of possible completion strings. - **cursor_start** (integer) - The starting position of the text being completed. - **cursor_end** (integer) - The ending position of the text being completed. - **metadata** (dict) - Optional metadata, potentially including experimental type information. - **_jupyter_types_experimental** (list) - List of dictionaries with completion details like 'text', 'type', and 'signature'. ``` -------------------------------- ### Code Inspection Reply Format Source: https://context7.com/ipython/ipykernel/llms.txt The reply from the kernel for a code inspection request. Contains found status and data with plain text and HTML representations of documentation. ```python inspect_reply = { 'status': 'ok', 'found': True, 'data': { 'text/plain': 'Signature: len(obj, /)\n' 'Docstring: Return the number of items in a container.', 'text/html': '
len(obj, /)

Return the number of items...

', }, 'metadata': {} } ``` -------------------------------- ### Code Inspection Request Format Source: https://context7.com/ipython/ipykernel/llms.txt Represents a code inspection request sent to the kernel. Specifies the code, cursor position, and detail level for documentation. ```python inspect_request = { 'content': { 'code': 'len', 'cursor_pos': 3, 'detail_level': 0, # 0 for signature, 1 for full docstring } } ``` -------------------------------- ### History Reply Format Source: https://context7.com/ipython/ipykernel/llms.txt The reply from the kernel for a history access request. Contains a list of history entries, each including session, line number, and the code input (or input/output pair). ```python history_reply = { 'status': 'ok', 'history': [ (1, 1, 'import numpy as np'), # (session, line, input) (1, 2, 'x = np.array([1,2,3])'), # With output=True: (session, line, (input, output)) ] } ``` -------------------------------- ### History Access: Tail Request Source: https://context7.com/ipython/ipykernel/llms.txt Request to retrieve the last N entries from the kernel's execution history. Can include or exclude output and specify raw or transformed code. ```python history_tail = { 'content': { 'output': False, 'raw': True, 'hist_access_type': 'tail', 'n': 10, # Last 10 entries } } ``` -------------------------------- ### Execute Request Message Structure Source: https://context7.com/ipython/ipykernel/llms.txt Defines the structure of an execute_request message sent to the kernel. Includes header, content with code to execute, and optional metadata. ```python execute_request = { 'header': { 'msg_type': 'execute_request', 'msg_id': 'unique-id', 'session': 'session-id', }, 'content': { 'code': 'print("Hello, World!")', 'silent': False, 'store_history': True, 'user_expressions': {}, 'allow_stdin': True, 'stop_on_error': True, }, 'metadata': { 'cellId': 'cell-uuid', # Optional cell identifier } } ``` -------------------------------- ### History Access API Source: https://context7.com/ipython/ipykernel/llms.txt API for accessing the kernel's execution history, including retrieving recent entries, ranges, or searching. ```APIDOC ## History Access API ### Description Provides access to the kernel's execution history. Supports retrieving the latest entries, a specific range, or searching based on a pattern. ### Method N/A (Message-based communication) ### Endpoint N/A (Message-based communication) ### Request Body (history_request) - **content** (dict) - **output** (boolean) - If True, includes execution output in the results. - **raw** (boolean) - If True, returns raw code; if False, returns transformed code. - **hist_access_type** (string) - Type of history access: 'tail', 'range', or 'search'. - **n** (integer) - (For 'tail' and 'search') The number of entries to retrieve. - **session** (integer) - (For 'range') The session ID to retrieve history from. - **start** (integer) - (For 'range') The starting line number. - **stop** (integer) - (For 'range') The stopping line number. - **pattern** (string) - (For 'search') The search pattern. - **unique** (boolean) - (For 'search') If True, returns only unique entries. ### Response (history_reply) - **status** (string) - 'ok' indicating success. - **history** (list) - A list of history entries. - Each entry is a tuple: (session_id, line_number, code_or_output). - If `output` is True, `code_or_output` is a tuple: (input_code, output_data). ``` -------------------------------- ### Execute Reply Message Structure Source: https://context7.com/ipython/ipykernel/llms.txt Defines the structure of an execute_reply message sent by the kernel. Indicates the status of execution and the execution count. ```python execute_reply = { 'header': { 'msg_type': 'execute_reply', }, 'content': { 'status': 'ok', # or 'error' 'execution_count': 1, # On error: # 'ename': 'NameError', # 'evalue': "name 'x' is not defined", # 'traceback': ['...'], } } ``` -------------------------------- ### Embed IPython Kernel in Application Source: https://context7.com/ipython/ipykernel/llms.txt Embeds an IPython kernel directly into a Python application, exposing local variables and configuration to connected Jupyter clients. Use `embed_kernel` and pass a dictionary to `local_ns`. ```python from ipykernel.embed import embed_kernel # Define some local variables you want exposed my_data = [1, 2, 3, 4, 5] config = {"setting": "value"} # Embed kernel - exposes current namespace to connected clients embed_kernel(local_ns={'data': my_data, 'config': config}) # Users connecting via Jupyter can now access: # >>> data # [1, 2, 3, 4, 5] # >>> config # {'setting': 'value'} ``` -------------------------------- ### Code Inspection API Source: https://context7.com/ipython/ipykernel/llms.txt API for inspecting code objects to retrieve documentation and type information. ```APIDOC ## Code Inspection API ### Description Allows inspection of code objects to retrieve documentation (docstrings) and type information. This is handled by the `do_inspect` method. ### Method N/A (Message-based communication) ### Endpoint N/A (Message-based communication) ### Request Body (inspect_request) - **content** (dict) - **code** (string) - The code object to inspect. - **cursor_pos** (integer) - The cursor's position within the code string. - **detail_level** (integer) - 0 for signature only, 1 for full docstring. ### Response (inspect_reply) - **status** (string) - 'ok' indicating success. - **found** (boolean) - True if inspection data was found, False otherwise. - **data** (dict) - A dictionary containing the inspection results in various MIME types. - **text/plain** (string) - Plain text representation of the signature and docstring. - **text/html** (string) - HTML representation of the signature and docstring. - **metadata** (dict) - Optional metadata. ``` -------------------------------- ### Stream Message Structure Source: https://context7.com/ipython/ipykernel/llms.txt Defines the structure of a stream message sent on IOPub, typically for stdout or stderr. Contains the name and text content. ```python stream_msg = { 'header': {'msg_type': 'stream'}, 'content': { 'name': 'stdout', # or 'stderr' 'text': 'Hello, World!\n', } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.