Skip to content

typing

Modules:

  • t_content –

    Provides typing definitions for message content.

Classes:

Attributes:

HandlerType module-attribute

HandlerType = Callable[[Job], Awaitable[t_content.T_reply_content_co | None]]

A TypeAlias for the handler of message requests.

T_content_co module-attribute

T_content_co = TypeVar('T_content_co', bound=Content, covariant=True, default=AnyContent)

T_interface_co module-attribute

T_interface_co = TypeVar(
    "T_interface_co", covariant=True, bound="Interface", default="Interface"
)

T_ipshell_co module-attribute

T_ipshell_co = TypeVar("T_ipshell_co", covariant=True, bound="IPShell", default="IPShell")

A Covariant typevar for an IPShell.

T_shell_co module-attribute

T_shell_co = TypeVar("T_shell_co", covariant=True, bound="BaseShell", default="BaseShell")

Backend

Bases: StrEnum

An enum of library names corresponding to anyio.

Attributes:

  • asyncio –

    An asyncio style event loop.

  • trio –

    A trio style event loop.

Source code in src/async_kernel/typing/_typing.py
70
71
72
73
74
75
76
77
class Backend(enum.StrEnum):
    """An enum of library names corresponding to anyio."""

    asyncio = "asyncio"
    """An asyncio style event loop."""

    trio = "trio"
    """A trio style event loop."""

asyncio class-attribute instance-attribute

asyncio = 'asyncio'

An asyncio style event loop.

trio class-attribute instance-attribute

trio = 'trio'

A trio style event loop.

CallerCreateOptions

Bases: RunSettings

Options to use when creating an instance of a Caller.

Attributes:

Source code in src/async_kernel/typing/_typing.py
587
588
589
590
591
592
593
594
class CallerCreateOptions(RunSettings):
    """Options to use when creating an instance of a [Caller][async_kernel.caller.Caller]."""

    name: NotRequired[str]
    """The name for the new caller instance."""

    no_debug: NotRequired[bool]
    """Disable debugpy in the thread if a new thread is created."""

name instance-attribute

The name for the new caller instance.

no_debug instance-attribute

no_debug: NotRequired[bool]

Disable debugpy in the thread if a new thread is created.

CallerState

Bases: Enum

The State of a async_kernel.caller.Caller.

Source code in src/async_kernel/typing/_typing.py
410
411
412
413
414
415
416
417
418
class CallerState(enum.Enum):
    """The State of a [async_kernel.caller.Caller][]."""

    initial = enum.auto()
    start_sync = enum.auto()
    starting = enum.auto()
    running = enum.auto()
    stopping = enum.auto()
    stopped = enum.auto()

Channel

Bases: StrEnum

An enum of channel names Ref.

Attributes:

Source code in src/async_kernel/typing/_typing.py
104
105
106
107
108
109
110
111
112
113
114
115
116
class Channel(enum.StrEnum):
    """An enum of channel names [Ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#introduction)."""

    heartbeat = "hb"
    """"""
    shell = "shell"
    """"""
    stdin = "stdin"
    """"""
    control = "control"
    """"""
    iopub = "iopub"
    """"""

heartbeat class-attribute instance-attribute

heartbeat = 'hb'

shell class-attribute instance-attribute

shell = 'shell'

stdin class-attribute instance-attribute

stdin = 'stdin'

control class-attribute instance-attribute

control = 'control'

iopub class-attribute instance-attribute

iopub = 'iopub'

FixedCreate

Bases: TypedDict, Generic[S]

A TypedDict relevant to Fixed.

Attributes:

Source code in src/async_kernel/typing/_typing.py
546
547
548
549
550
551
552
class FixedCreate(TypedDict, Generic[S]):
    """A TypedDict relevant to Fixed."""

    name: str
    """"""
    owner: S
    """"""

name instance-attribute

name: str

owner instance-attribute

owner: S

FixedCreated

Bases: TypedDict, Generic[S, T]

A TypedDict relevant to Fixed.

Attributes:

Source code in src/async_kernel/typing/_typing.py
555
556
557
558
559
560
561
562
563
class FixedCreated(TypedDict, Generic[S, T]):
    """A TypedDict relevant to Fixed."""

    name: str
    """"""
    owner: S
    """"""
    obj: T
    """"""

name instance-attribute

name: str

owner instance-attribute

owner: S

obj instance-attribute

obj: T

Hosts

Bases: StrEnum

An enum of host names that are available in async_kernel.event_loop.run.run.

Methods:

  • from_gui –

    Transform a matplotlib gui type to a host name if possible.

Attributes:

Source code in src/async_kernel/typing/_typing.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@final
class Hosts(enum.StrEnum):
    """An enum of host names that are available in [async_kernel.event_loop.run.run][]."""

    tk = "tk"
    """An eventloop for [tkinter][]."""

    qt = "qt"
    """An event loop for [Qt](https://wiki.qt.io/Qt_for_Python)."""

    custom = "custom"
    """A custom host."""

    @classmethod
    def from_gui(cls, gui: str | None, /) -> Hosts | None:
        """Transform a matplotlib gui type to a host name if possible."""
        if gui:
            if gui == "tk":
                return Hosts.tk
            if gui == "qt":
                return Hosts.qt
        return None

tk class-attribute instance-attribute

tk = 'tk'

An eventloop for tkinter.

qt class-attribute instance-attribute

qt = 'qt'

An event loop for Qt.

custom class-attribute instance-attribute

custom = 'custom'

A custom host.

from_gui classmethod

from_gui(gui: str | None) -> Hosts | None

Transform a matplotlib gui type to a host name if possible.

Source code in src/async_kernel/typing/_typing.py
 93
 94
 95
 96
 97
 98
 99
100
101
@classmethod
def from_gui(cls, gui: str | None, /) -> Hosts | None:
    """Transform a matplotlib gui type to a host name if possible."""
    if gui:
        if gui == "tk":
            return Hosts.tk
        if gui == "qt":
            return Hosts.qt
    return None

Job

Bases: TypedDict, Generic[T_content_co]

A Message request bundle.

Attributes:

Source code in src/async_kernel/typing/_typing.py
530
531
532
533
534
535
536
537
538
539
540
541
542
543
class Job(TypedDict, Generic[T_content_co]):
    """A `Message` request bundle."""

    msg: Message[T_content_co]
    """The message received over the socket."""

    ident: list[bytes]
    """The ident associated with the message and its origin."""

    owner: MessageProtocol
    """The local object which received message request."""

    received_time: float
    """The time the message was received."""

msg instance-attribute

The message received over the socket.

ident instance-attribute

ident: list[bytes]

The ident associated with the message and its origin.

owner instance-attribute

The local object which received message request.

received_time instance-attribute

received_time: float

The time the message was received.

Message

Bases: TypedDict, Generic[T_content_co]

A message.

Attributes:

Source code in src/async_kernel/typing/_typing.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
class Message(TypedDict, Generic[T_content_co]):
    """A [message](https://jupyter-client.readthedocs.io/en/stable/messaging.html#general-message-format)."""

    channel: Channel
    """The channel of the message."""

    header: MsgHeader
    """[ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header)"""

    parent_header: MsgHeader | None
    """[ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#parent-header)"""

    metadata: dict[str, Any]
    """[ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#metadata)"""

    content: T_content_co
    """[ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#metadata)

    **See Also**

        - [ExecuteRequest][]
    """
    buffers: BuffersType
    ""

channel instance-attribute

channel: Channel

The channel of the message.

header instance-attribute

header: MsgHeader

ref

parent_header instance-attribute

parent_header: MsgHeader | None

ref

metadata instance-attribute

metadata: dict[str, Any]

ref

content instance-attribute

content: T_content_co

ref

See Also

- [ExecuteRequest][]

buffers instance-attribute

buffers: BuffersType

MessageProtocol

Bases: Protocol

The protocol used by a connection and client to send data to the opposite side.

The data transmission is designed to be symmetric.

ident (a list of bytes) is provided for routing the message, in normal usage this is the session_id. ident is also used for iopub messages to provide one or more topics.

Methods:

  • msg –

    Create a new message.

  • handle_incoming_msg –

    The method where incoming messages are handled.

  • handle_reply –

    A handler for relies to requests that originated from this object.

  • send_message –

    Sends the message to the opposite side and return a PendingMessage.

  • send_reply –

    Send a reply to a job (a message of msg_type ending in '_request').

  • transmit_msg –

    The method that does the actual data transmission to the opposite side.

  • send_message_no_reply –

    Sends a message without expecting a reply.

Source code in src/async_kernel/typing/_typing.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
@runtime_checkable
class MessageProtocol(typing.Protocol, metaclass=MessageMeta):
    """The protocol used by a connection and client to send data to the opposite side.

    The data transmission is designed to be symmetric.

    `ident` (a list of bytes) is provided for routing the message, in normal usage this
    is the `session_id`. `ident` is also used for iopub messages to provide one or more `topics`.
    """

    def msg(
        self,
        msg_type: str | MsgType,
        content: T_content_co | dict[str, Any],
        channel: Channel,
        *,
        parent: Message | None = None,
        header: MsgHeader | dict[str, Any] | None = None,
        metadata: dict[str, Any] | None = None,
        buffers: BuffersType | None = None,
    ) -> Message[T_content_co]:
        """Create a new message."""
        ...

    def handle_incoming_msg(self, msg: Message, ident: list[bytes]) -> None:
        """The method where incoming messages are handled."""

    def handle_reply(self, msg: Message) -> None:
        """A handler for relies to requests that originated from this object."""

    def send_message(
        self,
        msg: Message,
        ident: bytes | list[bytes] | None = None,
    ) -> PendingMessage[t_content.T_reply_content_co]:
        """Sends the message to the opposite side and return a PendingMessage."""
        ...

    def send_reply(
        self, job: Job, content: t_content.T_reply_content_co, /, *, buffers: BuffersType | None = None
    ) -> None:
        """Send a reply to a job (a message of msg_type ending in '_request')."""

    def transmit_msg(self, msg: Message, ident: list[bytes]) -> None:
        """The method that does the actual data transmission to the opposite side."""

    def send_message_no_reply(self, msg: Message, ident: bytes | list[bytes] | None = None) -> None:
        """Sends a message without expecting a reply.

        This could be of two categories:
            1. The reply to a request.
            2. A message of a type that does not have a reply such as comm_open, comm_close, comm_msg.
        """
        ...

msg

msg(
    msg_type: str | MsgType,
    content: T_content_co | dict[str, Any],
    channel: Channel,
    *,
    parent: Message | None = None,
    header: MsgHeader | dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
    buffers: BuffersType | None = None,
) -> Message[T_content_co]

Create a new message.

Source code in src/async_kernel/typing/_typing.py
439
440
441
442
443
444
445
446
447
448
449
450
451
def msg(
    self,
    msg_type: str | MsgType,
    content: T_content_co | dict[str, Any],
    channel: Channel,
    *,
    parent: Message | None = None,
    header: MsgHeader | dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
    buffers: BuffersType | None = None,
) -> Message[T_content_co]:
    """Create a new message."""
    ...

handle_incoming_msg

handle_incoming_msg(msg: Message, ident: list[bytes]) -> None

The method where incoming messages are handled.

Source code in src/async_kernel/typing/_typing.py
453
454
def handle_incoming_msg(self, msg: Message, ident: list[bytes]) -> None:
    """The method where incoming messages are handled."""

handle_reply

handle_reply(msg: Message) -> None

A handler for relies to requests that originated from this object.

Source code in src/async_kernel/typing/_typing.py
456
457
def handle_reply(self, msg: Message) -> None:
    """A handler for relies to requests that originated from this object."""

send_message

send_message(
    msg: Message, ident: bytes | list[bytes] | None = None
) -> PendingMessage[T_reply_content_co]

Sends the message to the opposite side and return a PendingMessage.

Source code in src/async_kernel/typing/_typing.py
459
460
461
462
463
464
465
def send_message(
    self,
    msg: Message,
    ident: bytes | list[bytes] | None = None,
) -> PendingMessage[t_content.T_reply_content_co]:
    """Sends the message to the opposite side and return a PendingMessage."""
    ...

send_reply

send_reply(
    job: Job, content: T_reply_content_co, /, *, buffers: BuffersType | None = None
) -> None

Send a reply to a job (a message of msg_type ending in '_request').

Source code in src/async_kernel/typing/_typing.py
467
468
469
470
def send_reply(
    self, job: Job, content: t_content.T_reply_content_co, /, *, buffers: BuffersType | None = None
) -> None:
    """Send a reply to a job (a message of msg_type ending in '_request')."""

transmit_msg

transmit_msg(msg: Message, ident: list[bytes]) -> None

The method that does the actual data transmission to the opposite side.

Source code in src/async_kernel/typing/_typing.py
472
473
def transmit_msg(self, msg: Message, ident: list[bytes]) -> None:
    """The method that does the actual data transmission to the opposite side."""

send_message_no_reply

send_message_no_reply(msg: Message, ident: bytes | list[bytes] | None = None) -> None

Sends a message without expecting a reply.

This could be of two categories
  1. The reply to a request.
  2. A message of a type that does not have a reply such as comm_open, comm_close, comm_msg.
Source code in src/async_kernel/typing/_typing.py
475
476
477
478
479
480
481
482
def send_message_no_reply(self, msg: Message, ident: bytes | list[bytes] | None = None) -> None:
    """Sends a message without expecting a reply.

    This could be of two categories:
        1. The reply to a request.
        2. A message of a type that does not have a reply such as comm_open, comm_close, comm_msg.
    """
    ...

MsgHeader

Bases: TypedDict

A message header.

Attributes:

Source code in src/async_kernel/typing/_typing.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class MsgHeader(TypedDict):
    """A [message header](https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header)."""

    msg_id: str
    """"""
    session: str
    """"""
    username: str
    """"""
    date: str | datetime.datetime
    """"""
    msg_type: MsgType | str
    """"""
    version: str
    """"""
    subshell_id: NotRequired[str | None]
    """"""

msg_id instance-attribute

msg_id: str

session instance-attribute

session: str

username instance-attribute

username: str

date instance-attribute

date: str | datetime

msg_type instance-attribute

msg_type: MsgType | str

version instance-attribute

version: str

subshell_id instance-attribute

subshell_id: NotRequired[str | None]

MsgType

Bases: StrEnum

An enumeration of Message msg_type for shell and control messages.

Some message types are on the control channel only.

Attributes:

Source code in src/async_kernel/typing/_typing.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
class MsgType(enum.StrEnum):
    """An enumeration of Message `msg_type` for [shell and control messages]( https://jupyter-client.readthedocs.io/en/stable/messaging.html#messages-on-the-shell-router-dealer-channel).

    Some message types are on the [control channel](https://jupyter-client.readthedocs.io/en/stable/messaging.html#messages-on-the-control-router-dealer-channel) only.
    """

    kernel_info_request = "kernel_info_request"
    """[async_kernel.kernel.Kernel.kernel_info_request][]"""

    comm_info_request = "comm_info_request"
    """[async_kernel.kernel.Kernel.comm_info_request][]"""

    execute_request = "execute_request"
    """[async_kernel.kernel.Kernel.execute_request][]"""

    complete_request = "complete_request"
    """[async_kernel.kernel.Kernel.complete_request][]"""

    is_complete_request = "is_complete_request"
    """[async_kernel.kernel.Kernel.is_complete_request][]"""

    inspect_request = "inspect_request"
    """[async_kernel.kernel.Kernel.inspect_request][]"""

    history_request = "history_request"
    """[async_kernel.kernel.Kernel.history_request][]"""

    comm_open = "comm_open"
    """[async_kernel.kernel.Kernel.comm_open][]"""

    comm_msg = "comm_msg"
    """[async_kernel.kernel.Kernel.comm_msg][]"""

    comm_close = "comm_close"
    """[async_kernel.kernel.Kernel.comm_close][]"""

    # Control
    interrupt_request = "interrupt_request"
    """[async_kernel.kernel.Kernel.interrupt_request][] (control channel only)"""

    shutdown_request = "shutdown_request"
    """[async_kernel.kernel.Kernel.shutdown_request][] (control channel only)"""

    debug_request = "debug_request"
    """[async_kernel.kernel.Kernel.debug_request][] (control channel only)"""

    create_subshell_request = "create_subshell_request"
    """[async_kernel.kernel.Kernel.create_subshell_request][] (control channel only)"""

    delete_subshell_request = "delete_subshell_request"
    """[async_kernel.kernel.Kernel.delete_subshell_request][] (control channel only)"""

    list_subshell_request = "list_subshell_request"
    """[async_kernel.kernel.Kernel.debug_request][] (control channel only)"""

    # Reverse messaging (kernel -> client)
    input_request = "input_request"
    """A message sent from the kernel interface to a client asking for raw input."""

    # iopub messages (kernel -> client

    iopub_welcome = "iopub_welcome"
    """A welcome message on the iopub channel for new iopub channel subscriptions."""

    iopub_status = "status"
    """An iopub message about a handlers status which can be 'busy' or 'idle'."""

    iopub_error = "error"
    """An iopub message with error content."""

    iopub_execute_input = "execute_input"
    """An iopub message with detail of an execute request."""

    iopub_execute_result = "execute_result"
    """An iopub message with for the global display hook. Generally the last executed line of an execute request."""

    iopub_stream = "stream"
    """Stream data such as stdout and stderr."""

    iopub_display_data = "display_data"
    """An iopub message with display output data."""

    iopub_update_display_data = "iopub_update_display_data"
    """An iopub message to update display data."""

    iopub_clear_output = "clear_output"
    """An iopub display message instructing the associated display to clear."""

    debug_event = "debug_event"
    """An event published by an attached debug adapter."""

    # Reply messages (kernel -> client)
    kernel_info_reply = "kernel_info_reply"

    comm_info_reply = "comm_info_reply"

    execute_reply = "execute_reply"

    complete_reply = "complete_reply"

    is_complete_reply = "is_complete_reply"

    inspect_reply = "inspect_reply"

    history_reply = "history_reply"

    interrupt_reply = "interrupt_reply"

    shutdown_reply = "shutdown_reply"

    debug_reply = "debug_reply"

    create_subshell_reply = "create_subshell_reply"

    delete_subshell_reply = "delete_subshell_reply"

    list_subshell_reply = "list_subshell_reply"

    # Reverse reply (client -> kernel)
    input_reply = "input_reply"
    """A reply sent from the client to a kernel interface corresponding to an input request."""

kernel_info_request class-attribute instance-attribute

kernel_info_request = 'kernel_info_request'

comm_info_request class-attribute instance-attribute

comm_info_request = 'comm_info_request'

execute_request class-attribute instance-attribute

execute_request = 'execute_request'

complete_request class-attribute instance-attribute

complete_request = 'complete_request'

is_complete_request class-attribute instance-attribute

is_complete_request = 'is_complete_request'

inspect_request class-attribute instance-attribute

inspect_request = 'inspect_request'

history_request class-attribute instance-attribute

history_request = 'history_request'

comm_open class-attribute instance-attribute

comm_open = 'comm_open'

comm_msg class-attribute instance-attribute

comm_msg = 'comm_msg'

comm_close class-attribute instance-attribute

comm_close = 'comm_close'

interrupt_request class-attribute instance-attribute

interrupt_request = 'interrupt_request'

shutdown_request class-attribute instance-attribute

shutdown_request = 'shutdown_request'

debug_request class-attribute instance-attribute

debug_request = 'debug_request'

create_subshell_request class-attribute instance-attribute

create_subshell_request = 'create_subshell_request'

delete_subshell_request class-attribute instance-attribute

delete_subshell_request = 'delete_subshell_request'

list_subshell_request class-attribute instance-attribute

list_subshell_request = 'list_subshell_request'

input_request class-attribute instance-attribute

input_request = 'input_request'

A message sent from the kernel interface to a client asking for raw input.

iopub_welcome class-attribute instance-attribute

iopub_welcome = 'iopub_welcome'

A welcome message on the iopub channel for new iopub channel subscriptions.

iopub_status class-attribute instance-attribute

iopub_status = 'status'

An iopub message about a handlers status which can be 'busy' or 'idle'.

iopub_error class-attribute instance-attribute

iopub_error = 'error'

An iopub message with error content.

iopub_execute_input class-attribute instance-attribute

iopub_execute_input = 'execute_input'

An iopub message with detail of an execute request.

iopub_execute_result class-attribute instance-attribute

iopub_execute_result = 'execute_result'

An iopub message with for the global display hook. Generally the last executed line of an execute request.

iopub_stream class-attribute instance-attribute

iopub_stream = 'stream'

Stream data such as stdout and stderr.

iopub_display_data class-attribute instance-attribute

iopub_display_data = 'display_data'

An iopub message with display output data.

iopub_update_display_data class-attribute instance-attribute

iopub_update_display_data = 'iopub_update_display_data'

An iopub message to update display data.

iopub_clear_output class-attribute instance-attribute

iopub_clear_output = 'clear_output'

An iopub display message instructing the associated display to clear.

debug_event class-attribute instance-attribute

debug_event = 'debug_event'

An event published by an attached debug adapter.

input_reply class-attribute instance-attribute

input_reply = 'input_reply'

A reply sent from the client to a kernel interface corresponding to an input request.

RunMode

Bases: StrEnum

An Enum of the run modes available for handling execute_request messages.

Cell overrides

The user can also specify an execution mode in execute requests.

Top line comment:

# task
or

```python
# thread
```

Methods:

  • to_runmode –

    Converts value to Runmode, CallerCreateOptions or default where it is not possible.

  • line_to_options –

    Convert the line string to CallerCreateOptions.

Attributes:

Source code in src/async_kernel/typing/_typing.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class RunMode(enum.StrEnum):
    """An Enum of the run modes available for handling `execute_request` messages.

    Cell overrides:
        The user can also specify an execution mode in execute requests.

        Top line comment:
            ```python
            # task
            ```
            or

            ```python
            # thread
            ```
    """

    @override
    def __str__(self):
        return f"# {self.name}"

    @override
    def __eq__(self, value: object, /) -> bool:
        return str(value) in {self.name, str(self), repr(self)}

    @override
    def __hash__(self) -> int:
        return hash(self.name)

    @classmethod
    def to_runmode(cls, value: Any, default: T = None, /) -> Self | T | CallerCreateOptions:
        """Converts value to `Runmode`, `CallerCreateOptions` or  default where it is not possible.

        `CallerCreateOptions` will only return when a string is passed specifying a thread and options.

        Example:
            `value = "# thread name='My exeecutor' backend=trio`
        """
        try:
            return cls(value)
        except ValueError:
            if isinstance(value, str):
                if value.startswith(("# ", "##")):
                    return cls.to_runmode(value[2:].strip(), default)
                if value.startswith("thread"):
                    return cls.line_to_options(value.removeprefix("thread"))
            return default

    @classmethod
    def line_to_options(cls, line: str, /) -> CallerCreateOptions:
        """Convert the line string to CallerCreateOptions."""
        import shlex  # noqa: PLC0415

        items = CallerCreateOptions()
        for v in shlex.split(line):
            k, val = v.split("=", maxsplit=1)
            try:
                items[k] = eval(val)
            except Exception:
                items[k] = val
        if items and not items.get("name"):
            msg = "'name' must be specified when providing settings!"
            raise ValueError(msg)
        if invalid := set(items).difference(get_annotations(CallerCreateOptions)):
            msg = f"One or more invalid options found! valid={list(get_annotations(CallerCreateOptions))} invalid={list(invalid)}"
            raise ValueError(msg)
        return items

    queue = "queue"
    """Run the message handler using [async_kernel.caller.Caller.queue_call][]."""

    task = "task"
    """Run the message handler using [async_kernel.caller.Caller.call_soon][]."""

    thread = "thread"
    """Run the message handler using [async_kernel.caller.Caller.to_thread][]."""

queue class-attribute instance-attribute

queue = 'queue'

Run the message handler using async_kernel.caller.Caller.queue_call.

task class-attribute instance-attribute

task = 'task'

Run the message handler using async_kernel.caller.Caller.call_soon.

thread class-attribute instance-attribute

thread = 'thread'

Run the message handler using async_kernel.caller.Caller.to_thread.

to_runmode classmethod

to_runmode(value: Any, default: T = None) -> Self | T | CallerCreateOptions

Converts value to Runmode, CallerCreateOptions or default where it is not possible.

CallerCreateOptions will only return when a string is passed specifying a thread and options.

Example

value = "# thread name='My exeecutor' backend=trio

Source code in src/async_kernel/typing/_typing.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@classmethod
def to_runmode(cls, value: Any, default: T = None, /) -> Self | T | CallerCreateOptions:
    """Converts value to `Runmode`, `CallerCreateOptions` or  default where it is not possible.

    `CallerCreateOptions` will only return when a string is passed specifying a thread and options.

    Example:
        `value = "# thread name='My exeecutor' backend=trio`
    """
    try:
        return cls(value)
    except ValueError:
        if isinstance(value, str):
            if value.startswith(("# ", "##")):
                return cls.to_runmode(value[2:].strip(), default)
            if value.startswith("thread"):
                return cls.line_to_options(value.removeprefix("thread"))
        return default

line_to_options classmethod

line_to_options(line: str) -> CallerCreateOptions

Convert the line string to CallerCreateOptions.

Source code in src/async_kernel/typing/_typing.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
@classmethod
def line_to_options(cls, line: str, /) -> CallerCreateOptions:
    """Convert the line string to CallerCreateOptions."""
    import shlex  # noqa: PLC0415

    items = CallerCreateOptions()
    for v in shlex.split(line):
        k, val = v.split("=", maxsplit=1)
        try:
            items[k] = eval(val)
        except Exception:
            items[k] = val
    if items and not items.get("name"):
        msg = "'name' must be specified when providing settings!"
        raise ValueError(msg)
    if invalid := set(items).difference(get_annotations(CallerCreateOptions)):
        msg = f"One or more invalid options found! valid={list(get_annotations(CallerCreateOptions))} invalid={list(invalid)}"
        raise ValueError(msg)
    return items

RunSettings

Bases: TypedDict

A dict of settings to use with async_kernel.event_loop.run.

Attributes:

Source code in src/async_kernel/typing/_typing.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
class RunSettings(TypedDict):
    """A dict of settings to use with [async_kernel.event_loop.run][]."""

    backend: NotRequired[Backend | Literal["asyncio", "trio"]]
    """The backend to use for the caller."""

    backend_options: NotRequired[dict | None]
    """The backend options to specify for [anyio.run][] (or `start_guest_run` when a host is specified).

    Tip:
        When there is no host and the backend is asyncio. 'loop_factory' can be specified as a function
        or importable path like `'asyncio.new_event_loop'`.
    """

    host: NotRequired[Hosts | Literal["tk", "qt"] | None]
    """The type of host where the backend will run."""

    host_options: NotRequired[dict | None]
    """Options to use when starting the host."""

backend instance-attribute

backend: NotRequired[Backend | Literal['asyncio', 'trio']]

The backend to use for the caller.

backend_options instance-attribute

backend_options: NotRequired[dict | None]

The backend options to specify for anyio.run (or start_guest_run when a host is specified).

Tip

When there is no host and the backend is asyncio. 'loop_factory' can be specified as a function or importable path like 'asyncio.new_event_loop'.

host instance-attribute

host: NotRequired[Hosts | Literal['tk', 'qt'] | None]

The type of host where the backend will run.

host_options instance-attribute

host_options: NotRequired[dict | None]

Options to use when starting the host.

Tags

Bases: StrEnum

Cell tags used in async-kernel.

Info

Tags are can be added per cell.

Methods:

  • get_value –

    Extract the value and convert it to match the type of default using tag=value.

Attributes:

  • raises_exception –

    Indicates the cell should expect an exception to be raised.

  • stop_on_error –

    Override stop_on_error.

  • timeout –

    Specify a timeout in seconds for code execution to complete.

Source code in src/async_kernel/typing/_typing.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
class Tags(enum.StrEnum):
    """Cell tags used in async-kernel.

    Info:
        Tags are can be added per cell.

        - Jupyter: via the [right side bar](https://jupyterlab.readthedocs.io/en/stable/user/interface.html#left-and-right-sidebar).
        - VS Code: via [Jupyter variables explorer](https://code.visualstudio.com/docs/python/jupyter-support-py#_variables-explorer-and-data-viewer)
    """

    @override
    def __eq__(self, value: object, /) -> bool:
        return str(value).replace("-", "_").split("=")[0] == self.name

    @override
    def __hash__(self) -> int:
        return hash(self.name)

    @classmethod
    def get_value(cls, value: str, default: T_fsb) -> T_fsb:
        """Extract the value and convert it to match the type of default using `tag=value`."""
        try:
            value = value.split("=")[1].strip()
        except Exception:
            return default
        try:
            if isinstance(default, bool):
                return value.lower() == "true"
            if isinstance(default, int):
                return int(value)
            if isinstance(default, float):
                return float(value)
            if isinstance(default, str):  # pyright: ignore[reportUnnecessaryIsInstance]
                return value
        except Exception:
            return default
        msg = "default must be a one of string, int, float, bool."  # pyright: ignore[reportUnreachable]
        raise ValueError(msg)

    raises_exception = "raises-exception"
    """Indicates the cell should expect an exception to be raised. 

    Notes:
        - When an exception is raised, stop_on_error is False/
        - When an exception is **not** raised an exception will be raise and stop_on_error is True.
    """

    stop_on_error = "stop-on-error"
    """Override `stop_on_error`.

    Examples:

        - True
            - stop_on_error=true
            - stop_on_error=True
        - False
            - stop_on_error=False
    """

    timeout = "timeout"
    """Specify a timeout in seconds for code execution to complete.

    Examples:

        - timeout=0.0 (no timeout)
        - timeout=0.1 (100 ms)
    """

raises_exception class-attribute instance-attribute

raises_exception = 'raises-exception'

Indicates the cell should expect an exception to be raised.

Notes
  • When an exception is raised, stop_on_error is False/
  • When an exception is not raised an exception will be raise and stop_on_error is True.

stop_on_error class-attribute instance-attribute

stop_on_error = 'stop-on-error'

Override stop_on_error.

Examples:

- True
    - stop_on_error=true
    - stop_on_error=True
- False
    - stop_on_error=False

timeout class-attribute instance-attribute

timeout = 'timeout'

Specify a timeout in seconds for code execution to complete.

Examples:

- timeout=0.0 (no timeout)
- timeout=0.1 (100 ms)

get_value classmethod

get_value(value: str, default: T_fsb) -> T_fsb

Extract the value and convert it to match the type of default using tag=value.

Source code in src/async_kernel/typing/_typing.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
@classmethod
def get_value(cls, value: str, default: T_fsb) -> T_fsb:
    """Extract the value and convert it to match the type of default using `tag=value`."""
    try:
        value = value.split("=")[1].strip()
    except Exception:
        return default
    try:
        if isinstance(default, bool):
            return value.lower() == "true"
        if isinstance(default, int):
            return int(value)
        if isinstance(default, float):
            return float(value)
        if isinstance(default, str):  # pyright: ignore[reportUnnecessaryIsInstance]
            return value
    except Exception:
        return default
    msg = "default must be a one of string, int, float, bool."  # pyright: ignore[reportUnreachable]
    raise ValueError(msg)

Provides typing definitions for message content.

Classes:

Attributes:

T_content_co module-attribute

T_content_co = TypeVar('T_content_co', bound=Content, covariant=True, default=AnyContent)

T_reply_content_co module-attribute

T_reply_content_co = TypeVar(
    "T_reply_content_co", bound=ReplyContent_, covariant=True, default=AnyReplyContent
)

A typevar for message content.

Content

Bases: TypedDict

Content in a message.

Source code in src/async_kernel/typing/_content.py
10
11
class Content(TypedDict):
    """Content in a message."""

AnyContent

Bases: TypedDict

Generic content when the type has not been defined.

Source code in src/async_kernel/typing/_content.py
14
15
class AnyContent(TypedDict, extra_items=ReadOnly[Any]):
    """Generic content when the type has not been defined."""

ReplyContent_

Bases: Content

Source code in src/async_kernel/typing/_content.py
22
23
class ReplyContent_(Content):
    """"""

ErrorReply

Bases: ReplyContent_

Content of a reply to a request that is an error.

Source code in src/async_kernel/typing/_content.py
30
31
32
33
34
35
36
class ErrorReply(ReplyContent_):
    """Content of a reply to a request that is an error."""

    status: Literal["error"]
    ename: str
    evalue: str
    traceback: list[str]

AnyReplyContent

Bases: ReplyContent

Source code in src/async_kernel/typing/_content.py
39
40
class AnyReplyContent(ReplyContent, extra_items=Any):
    """"""

HelpLinkType

Bases: TypedDict

Help links to display in the notebook.

Attributes:

Source code in src/async_kernel/typing/_content.py
51
52
53
54
55
56
57
class HelpLinkType(TypedDict):
    """Help links to display in the notebook."""

    text: str
    """"""
    url: str
    """"""

text instance-attribute

text: str

url instance-attribute

url: str

LanguageInfo

Bases: TypedDict

Used in KernelInfoReply.

Attributes:

Source code in src/async_kernel/typing/_content.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class LanguageInfo(TypedDict):
    """Used in `KernelInfoReply`."""

    name: str
    """Name of the programming language."""

    version: str
    """Language version number eg: 'X.Y.Z'."""

    mimetype: str
    """_mimetype_ for script files in this language."""

    file_extension: str
    """Extension including the dot, e.g. '.py'."""

    pygments_lexer: NotRequired[str]
    """Pygments lexer, for highlighting (Only needed if it differs from the 'name' field)."""

    codemirror_mode: NotRequired[str | dict[str, Any]]
    """Codemirror mode, for highlighting in the notebook, (Only needed if it differs from the 'name' field)."""

    nbconvert_exporter: NotRequired[str]
    """Nbconvert exporter, if notebooks written with this kernel should be exported with something other than the general 'script' exporter."""

name instance-attribute

name: str

Name of the programming language.

version instance-attribute

version: str

Language version number eg: 'X.Y.Z'.

mimetype instance-attribute

mimetype: str

mimetype for script files in this language.

file_extension instance-attribute

file_extension: str

Extension including the dot, e.g. '.py'.

pygments_lexer instance-attribute

pygments_lexer: NotRequired[str]

Pygments lexer, for highlighting (Only needed if it differs from the 'name' field).

codemirror_mode instance-attribute

codemirror_mode: NotRequired[str | dict[str, Any]]

Codemirror mode, for highlighting in the notebook, (Only needed if it differs from the 'name' field).

nbconvert_exporter instance-attribute

nbconvert_exporter: NotRequired[str]

Nbconvert exporter, if notebooks written with this kernel should be exported with something other than the general 'script' exporter.

KernelInfoRequest

Bases: RequestContent

Source code in src/async_kernel/typing/_content.py
86
87
class KernelInfoRequest(RequestContent):
    """"""

KernelInfoReply

Bases: ReplyContent

Attributes:

Source code in src/async_kernel/typing/_content.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
class KernelInfoReply(ReplyContent):
    protocol_version: str
    "Version of messaging protocol."

    implementation: str
    """The version number of the kernel's implementation."""

    implementation_version: str
    """The version of the kernel (module) eg: 'X.Y.Z'."""

    language_info: LanguageInfo
    """Information about the language of code for the kernel."""

    banner: str
    """A banner of information about the kernel which may be displayed in console environments."""

    help_links: list[HelpLinkType]
    """A mapping of help links to display in the notebook."""

    supported_features: list[str]
    """A list of optional features such as 'debugger."""

protocol_version instance-attribute

protocol_version: str

Version of messaging protocol.

implementation instance-attribute

implementation: str

The version number of the kernel's implementation.

implementation_version instance-attribute

implementation_version: str

The version of the kernel (module) eg: 'X.Y.Z'.

language_info instance-attribute

language_info: LanguageInfo

Information about the language of code for the kernel.

banner instance-attribute

banner: str

A banner of information about the kernel which may be displayed in console environments.

help_links: list[HelpLinkType]

A mapping of help links to display in the notebook.

supported_features instance-attribute

supported_features: list[str]

A list of optional features such as 'debugger.

CommInfoItem

Bases: TypedDict

Attributes:

Source code in src/async_kernel/typing/_content.py
114
115
116
117
118
class CommInfoItem(TypedDict):
    """"""

    target_name: str
    """"""

target_name instance-attribute

target_name: str

CommInfoRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
121
122
123
124
125
class CommInfoRequest(RequestContent):
    """"""

    target_name: NotRequired[str]
    """"""

target_name instance-attribute

target_name: NotRequired[str]

CommInfoReply

Bases: ReplyContent

A reply to a CommInfo request.

Attributes:

Source code in src/async_kernel/typing/_content.py
128
129
130
131
132
class CommInfoReply(ReplyContent):
    """A reply to a CommInfo request."""

    comms: dict[str, CommInfoItem]
    """A dictionary of the comms, indexed by the comm id (UUID)."""

comms instance-attribute

A dictionary of the comms, indexed by the comm id (UUID).

ExecuteRequest

Bases: RequestContent

Ref.

Attributes:

Source code in src/async_kernel/typing/_content.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class ExecuteRequest(RequestContent):
    """[Ref](https://jupyter-client.readthedocs.io/en/stable/messaging.html#execute)."""

    code: str
    """The code to execute."""
    silent: bool
    """"""
    store_history: bool
    """"""
    allow_stdin: bool
    """"""
    stop_on_error: bool
    """"""
    subshell_id: NotRequired[str | None]
    """"""
    user_expressions: NotRequired[dict[str, str]]
    """"""

code instance-attribute

code: str

The code to execute.

silent instance-attribute

silent: bool

store_history instance-attribute

store_history: bool

allow_stdin instance-attribute

allow_stdin: bool

stop_on_error instance-attribute

stop_on_error: bool

subshell_id instance-attribute

subshell_id: NotRequired[str | None]

user_expressions instance-attribute

user_expressions: NotRequired[dict[str, str]]

ExecuteReply

Bases: ReplyContent

Attributes:

Source code in src/async_kernel/typing/_content.py
160
161
162
163
164
165
166
167
class ExecuteReply(ReplyContent):
    """"""

    execution_count: int
    """"""

    user_expressions: dict[str, MIMEBundle]
    """"""

execution_count instance-attribute

execution_count: int

user_expressions instance-attribute

user_expressions: dict[str, MIMEBundle]

ExecuteErrorReply

Bases: ErrorReply

Attributes:

Source code in src/async_kernel/typing/_content.py
170
171
172
173
174
175
176
class ExecuteErrorReply(ErrorReply):
    """"""

    execution_count: int
    """"""
    user_expressions: dict[str, MIMEBundle]
    """"""

execution_count instance-attribute

execution_count: int

user_expressions instance-attribute

user_expressions: dict[str, MIMEBundle]

CompleteRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
180
181
182
183
184
185
186
187
class CompleteRequest(RequestContent):
    """"""

    code: str
    """"""

    cursor_pos: int | None
    """"""

code instance-attribute

code: str

cursor_pos instance-attribute

cursor_pos: int | None

CompleteReply

Bases: ReplyContent

Source code in src/async_kernel/typing/_content.py
190
191
192
193
194
195
196
class CompleteReply(ReplyContent):
    """"""

    matches: list
    cursor_end: int
    cursor_start: int
    metadata: NotRequired[dict]

InterruptRequest

Bases: RequestContent

Source code in src/async_kernel/typing/_content.py
200
201
class InterruptRequest(RequestContent):
    """"""

InterruptReply

Bases: ReplyContent

Source code in src/async_kernel/typing/_content.py
204
205
class InterruptReply(ReplyContent):
    """"""

ShutdownRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
209
210
211
212
213
class ShutdownRequest(RequestContent):
    """"""

    restart: bool
    """"""

restart instance-attribute

restart: bool

ShutdownReply

Bases: ReplyContent

A reply to a shutdown request.

Attributes:

Source code in src/async_kernel/typing/_content.py
216
217
218
219
220
class ShutdownReply(ReplyContent):
    """A reply to a shutdown request."""

    restart: bool
    """If restart is expected."""

restart instance-attribute

restart: bool

If restart is expected.

IsCompleteRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
224
225
226
227
228
class IsCompleteRequest(RequestContent):
    """"""

    code: str
    """"""

code instance-attribute

code: str

IsCompleteReply

Bases: ReplyContent_

A reply to an is_complete_request. https://jupyter-client.readthedocs.io/en/stable/messaging.html#code-completeness.

Source code in src/async_kernel/typing/_content.py
231
232
233
234
235
class IsCompleteReply(ReplyContent_):
    """A reply to an `is_complete_request`. https://jupyter-client.readthedocs.io/en/stable/messaging.html#code-completeness."""

    status: Literal["complete", "incomplete", "invalid", "unknown"]
    indent: NotRequired[str]

InspectRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
239
240
241
242
243
244
245
246
247
class InspectRequest(RequestContent):
    """"""

    code: str
    """"""
    cursor_pos: int | None
    """"""
    detail_level: int
    """"""

code instance-attribute

code: str

cursor_pos instance-attribute

cursor_pos: int | None

detail_level instance-attribute

detail_level: int

InspectReply

Bases: ReplyContent

Attributes:

Source code in src/async_kernel/typing/_content.py
250
251
252
253
254
255
256
257
258
class InspectReply(ReplyContent):
    """"""

    data: dict[str, Any]
    """"""
    metadata: dict[str, Any]
    """"""
    found: bool
    """"""

data instance-attribute

data: dict[str, Any]

metadata instance-attribute

metadata: dict[str, Any]

found instance-attribute

found: bool

HistoryRequest

Bases: RequestContent

Attributes:

  • output (bool) –

    If True, also return output history in the resulting dict.

  • raw (bool) –

    If True, return the raw input history, else the transformed input.

Source code in src/async_kernel/typing/_content.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
class HistoryRequest(RequestContent):
    """"""

    output: bool
    """ If True, also return output history in the resulting dict."""

    raw: bool
    """If True, return the raw input history, else the transformed input."""

    hist_access_type: str
    # So far, this can be 'range', 'tail' or 'search'.
    # If hist_access_type is 'range', get a range of input cells. session
    # is a number counting up each time the kernel starts; you can give
    # a positive session number, or a negative number to count back from
    # the current session.

    session: NotRequired[int]
    start: NotRequired[int]
    stop: NotRequired[int]
    # start and stop are line (cell) numbers within that session.

    # If hist_access_type is 'tail' or 'search', get the last n cells.
    n: NotRequired[int]

    # If hist_access_type is 'search', get cells matching the specified glob
    # pattern (with * and ? as wildcards).
    pattern: NotRequired[str]

    # If hist_access_type is 'search' and unique is true, do not
    # include duplicated history.  Default is false.
    unique: NotRequired[bool]

output instance-attribute

output: bool

If True, also return output history in the resulting dict.

raw instance-attribute

raw: bool

If True, return the raw input history, else the transformed input.

HistoryReply

Bases: ReplyContent

Source code in src/async_kernel/typing/_content.py
295
296
297
298
class HistoryReply(ReplyContent):
    """"""

    history: list[tuple]

InputRequest

Bases: RequestContent

Attributes:

Source code in src/async_kernel/typing/_content.py
302
303
304
305
306
307
308
class InputRequest(RequestContent):
    """"""

    prompt: str
    """"""
    password: bool
    """"""

prompt instance-attribute

prompt: str

password instance-attribute

password: bool

InputReply

Bases: ReplyContent

A reply to an input request.

Attributes:

Source code in src/async_kernel/typing/_content.py
311
312
313
314
315
class InputReply(ReplyContent):
    """A reply to an input request."""

    value: str
    ""

value instance-attribute

value: str

DebugRequest

Bases: RequestContent

A TypeAlias for a debug message.

Attributes:

Source code in src/async_kernel/typing/_content.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class DebugRequest(RequestContent, extra_items=Any):
    """A TypeAlias for a debug message."""

    seq: int
    """"""

    type: Literal["request"]
    """"""

    command: Literal["inspectVariables", "threads", "evaluate", "configurationDone"]
    """"""

    arguments: dict[str, Any]
    """"""

seq instance-attribute

seq: int

type instance-attribute

type: Literal['request']

command instance-attribute

command: Literal['inspectVariables', 'threads', 'evaluate', 'configurationDone']

arguments instance-attribute

arguments: dict[str, Any]

CreateSubshellRequest

Bases: RequestContent

Source code in src/async_kernel/typing/_content.py
340
341
class CreateSubshellRequest(RequestContent):
    """"""

CreateSubshellReply

Bases: ReplyContent

Attributes:

Source code in src/async_kernel/typing/_content.py
344
345
346
347
348
class CreateSubshellReply(ReplyContent):
    """"""

    subshell_id: str
    """"""

subshell_id instance-attribute

subshell_id: str

DeleteSubshellRequest

Bases: RequestContent

Source code in src/async_kernel/typing/_content.py
352
353
class DeleteSubshellRequest(RequestContent):
    """"""

DeleteSubshellReply

Bases: ReplyContent

Source code in src/async_kernel/typing/_content.py
356
357
class DeleteSubshellReply(ReplyContent):
    """"""

ListSubshellRequest

Bases: RequestContent

Source code in src/async_kernel/typing/_content.py
361
362
class ListSubshellRequest(RequestContent):
    """"""

ListSubshellReply

Bases: ReplyContent

Attributes:

Source code in src/async_kernel/typing/_content.py
365
366
367
368
369
class ListSubshellReply(ReplyContent):
    """"""

    subshell_id: list[str]
    """"""

subshell_id instance-attribute

subshell_id: list[str]