Skip to content

pending

Classes:

PendingCancelled

Bases: ClosedResourceError

Used to indicate the pending is cancelled.

Source code in src/async_kernel/pending.py
33
34
class PendingCancelled(anyio.ClosedResourceError):
    "Used to indicate the pending is cancelled."

InvalidStateError

Bases: RuntimeError

An invalid state of the pending.

Source code in src/async_kernel/pending.py
37
38
class InvalidStateError(RuntimeError):
    "An invalid state of the pending."

PendingTracker

The base class for tracking Pending.

Methods:

  • current

    The instance of the active tracker in the current context.

  • active_id

    The id of the active tracker in the current context.

  • add

    Track Pending until it is done.

Attributes:

Source code in src/async_kernel/pending.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class PendingTracker:
    """
    The base class for tracking [Pending][async_kernel.pending.Pending].
    """

    _subclasses: ClassVar[tuple[type[Self], ...]] = ()
    _instances: ClassVar[weakref.WeakValueDictionary[str, Self]] = weakref.WeakValueDictionary()
    _id_contextvar: ClassVar[contextvars.ContextVar[str | None]]
    _pending: Fixed[Self, set[Pending[Any]]] = Fixed(set)

    id: Fixed[Self, str] = Fixed(lambda _: str(uuid.uuid4()))
    """The unique id of the pending tracker instance."""

    @property
    def pending(self) -> set[Pending[Any]]:
        "The pending currently associated with this instance."
        return self._pending.copy()

    def __init_subclass__(cls) -> None:
        if cls.__name__ != "PendingManager":
            PendingTracker._subclasses = (*cls._subclasses, cls)
            # Each subclass is assigned a new context variable.
            cls._id_contextvar = contextvars.ContextVar(f"{cls.__module__}.{cls.__name__}", default=None)
        return super().__init_subclass__()

    @classmethod
    def current(cls) -> Self | None:
        "The instance of the active tracker in the current context."
        if (id_ := cls._id_contextvar.get()) and (current := cls._instances.get(id_)):
            return current
        return None

    @classmethod
    def active_id(cls) -> str | None:
        "The id of the active tracker in the current context."
        return cls._id_contextvar.get()

    def __init__(self) -> None:
        self._instances[self.id] = self

    def _activate(self) -> Token[str | None]:
        try:
            return self._id_contextvar.set(self.id)
        except AttributeError as e:
            e.add_note("Pending tracker must be subclassed to use it!")
            raise

    def _deactivate(self, token: contextvars.Token[str | None]) -> None:
        self._id_contextvar.reset(token)

    def add(self, pen: Pending) -> None:
        "Track `Pending` until it is done."

        if pen not in self._pending:
            self._pending.add(pen)
            pen.add_done_callback(self._on_pending_done)

    def _on_pending_done(self, pen: Pending) -> None:
        "A done_callback that is registered with pen when it is added (don't call directly)."
        self._pending.discard(pen)

id class-attribute instance-attribute

id: Fixed[Self, str] = Fixed(lambda _: str(uuid4()))

The unique id of the pending tracker instance.

pending property

pending: set[Pending[Any]]

The pending currently associated with this instance.

current classmethod

current() -> Self | None

The instance of the active tracker in the current context.

Source code in src/async_kernel/pending.py
66
67
68
69
70
71
@classmethod
def current(cls) -> Self | None:
    "The instance of the active tracker in the current context."
    if (id_ := cls._id_contextvar.get()) and (current := cls._instances.get(id_)):
        return current
    return None

active_id classmethod

active_id() -> str | None

The id of the active tracker in the current context.

Source code in src/async_kernel/pending.py
73
74
75
76
@classmethod
def active_id(cls) -> str | None:
    "The id of the active tracker in the current context."
    return cls._id_contextvar.get()

add

add(pen: Pending) -> None

Track Pending until it is done.

Source code in src/async_kernel/pending.py
91
92
93
94
95
96
def add(self, pen: Pending) -> None:
    "Track `Pending` until it is done."

    if pen not in self._pending:
        self._pending.add(pen)
        pen.add_done_callback(self._on_pending_done)

PendingManager

Bases: PendingTracker

Tracks the creation of Pending in multiple contexts.

This class must be subclassed to be useful.

For each subclass there is zero or one active trackers at a time. Activating a manager will 'replace' a previously active pending manager.

Notes:

- It must be subclassed.
- Each subclass is assigned one context variable.
    - This means that only one instance of the subclass can be active in a specific context at any time.
- It is linearly proportionally expensive to subclass PendingManager so it's usage should
    be limited to cases where it is necessary where the exact functionality is required.

Usage:

```python
class MyPendingManager(PendingManager):
    "Manages the context of ..."


m = MyPendingManager()
m2 = MyPendingManager()

# In one or more contexts
token = m.activate()
try:
    ...
    try:
        token2 = m2.activate()
        pen = m2.caller.call_soon(lambda: 1 + 1)
        assert pen in m2.pending
        assert (
            pen not in m.pending
        ), "pen is associated should only be associated with m2"
        ...
    finally:
        m2.deactivate(token2)

finally:
    m.deactivate(token)
```

Methods:

  • activate

    Start tracking Pending in the current context.

  • deactivate

    Stop tracking.

  • remove

    Remove a pending from the manager.

  • context

    A context manager where the pending manager is activated.

Source code in src/async_kernel/pending.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
class PendingManager(PendingTracker):
    """
    Tracks the creation of `Pending` in multiple contexts.

    This class must be subclassed to be useful.

    For each subclass there is zero or one active trackers at a time. Activating a manager will 'replace' a
    previously active pending manager.

    Notes:

        - It must be subclassed.
        - Each subclass is assigned one context variable.
            - This means that only one instance of the subclass can be active in a specific context at any time.
        - It is linearly proportionally expensive to subclass PendingManager so it's usage should
            be limited to cases where it is necessary where the exact functionality is required.

    Usage:

        ```python
        class MyPendingManager(PendingManager):
            "Manages the context of ..."


        m = MyPendingManager()
        m2 = MyPendingManager()

        # In one or more contexts
        token = m.activate()
        try:
            ...
            try:
                token2 = m2.activate()
                pen = m2.caller.call_soon(lambda: 1 + 1)
                assert pen in m2.pending
                assert (
                    pen not in m.pending
                ), "pen is associated should only be associated with m2"
                ...
            finally:
                m2.deactivate(token2)

        finally:
            m.deactivate(token)
        ```
    """

    def activate(self) -> contextvars.Token[str | None]:
        """
        Start tracking `Pending` in the  current context.
        """
        return self._activate()

    def deactivate(self, token: contextvars.Token[str | None]) -> None:
        """
        Stop tracking.

        Args:
            token: The token returned from [activate][].
        """
        self._deactivate(token)

    def remove(self, pen: Pending) -> None:
        """
        Remove a pending from the manager.
        """
        self._pending.remove(pen)

    @contextlib.contextmanager
    def context(self) -> Generator[None, Any, None]:
        """A context manager where the pending manager is activated."""
        token = self.activate()
        try:
            yield
        finally:
            self.deactivate(token)

activate

activate() -> Token[str | None]

Start tracking Pending in the current context.

Source code in src/async_kernel/pending.py
150
151
152
153
154
def activate(self) -> contextvars.Token[str | None]:
    """
    Start tracking `Pending` in the  current context.
    """
    return self._activate()

deactivate

deactivate(token: Token[str | None]) -> None

Stop tracking.

Parameters:

Source code in src/async_kernel/pending.py
156
157
158
159
160
161
162
163
def deactivate(self, token: contextvars.Token[str | None]) -> None:
    """
    Stop tracking.

    Args:
        token: The token returned from [activate][].
    """
    self._deactivate(token)

remove

remove(pen: Pending) -> None

Remove a pending from the manager.

Source code in src/async_kernel/pending.py
165
166
167
168
169
def remove(self, pen: Pending) -> None:
    """
    Remove a pending from the manager.
    """
    self._pending.remove(pen)

context

context() -> Generator[None, Any, None]

A context manager where the pending manager is activated.

Source code in src/async_kernel/pending.py
171
172
173
174
175
176
177
178
@contextlib.contextmanager
def context(self) -> Generator[None, Any, None]:
    """A context manager where the pending manager is activated."""
    token = self.activate()
    try:
        yield
    finally:
        self.deactivate(token)

PendingGroup

Bases: PendingTracker, AsyncContextManagerMixin

An asynchronous context manager for tracking Pending that are created in it's context.

Usage

Enter the async context and create new pending.

async with PendingGroup() as pg:
    assert pg.caller.to_thread(lambda: None) in pg.pending

Methods:

  • __init__

    An async context to capture all pending (that opt in) created in the context.

  • cancel

    Cancel the pending group (internally synchronised).

  • cancelled

    Returns: If the pending group is marked as cancelled.

Attributes:

Source code in src/async_kernel/pending.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
@final
class PendingGroup(PendingTracker, anyio.AsyncContextManagerMixin):
    """
    An asynchronous context manager for tracking `Pending` that are created in it's context.

    Usage:
        Enter the async context and create new pending.

        ```python
        async with PendingGroup() as pg:
            assert pg.caller.to_thread(lambda: None) in pg.pending
        ```
    """

    _parent_id: None | str = None
    _cancel_scope: anyio.CancelScope
    _cancelled: str | None = None
    _leaving_context: bool = False
    _failed: Fixed[Self, list[Pending]] = Fixed(list)
    cancellation_timeout = 10
    "The maximum time to wait for cancelled pending to be done."

    caller: Fixed[Self, Caller] = Fixed(lambda _: async_kernel.Caller())
    "The caller where the pending group was instantiated."

    def __init__(self, *, shield: bool = False, mode: int = 0) -> None:
        """
        An async context to capture all pending (that opt in) created in the context.

        The pending group will only exit once all pending in the group are `done`.

        Pending can be added to and removed from the group manually.

        Args:
            shield: Passed to the cancel scope.
            mode: The mode.
                - 0: Ignore cancellation of pending.
                - 1: Cancel if any pending is cancelled - raise PendingCancelled on exit.
                - 2: Cancel if any pending is cancelled - exit quietly.
        """
        assert mode in [0, 1, 2]
        self._mode = mode
        self._shield = shield
        self.caller  # noqa: B018
        super().__init__()

    @override
    def __repr__(self) -> str:
        info = " ⛔ cancelled" if self._cancelled else ""
        return f"<PendingGroup at {id(self)}{info} | {len(self.pending)} pending | mode:{self._mode}>"

    @override
    def _activate(self) -> Token[str | None]:
        self._parent_id = None if (parent_id := self._id_contextvar.get()) == self.id else parent_id
        return super()._activate()

    @contextlib.asynccontextmanager
    async def __asynccontextmanager__(self) -> AsyncGenerator[Self]:
        if self._leaving_context:
            msg = f"Re-entry of {self.__class__} is not supported!"
            raise InvalidStateError(msg)
        self._cancel_scope = anyio.CancelScope(shield=self._shield)
        self._all_done = create_async_event()
        token = self._activate()
        try:
            with self._cancel_scope:
                try:
                    yield self
                    self._leaving_context = True
                    if self._pending:
                        await self._all_done
                except (anyio.get_cancelled_exc_class(), Exception) as e:
                    self.cancel(f"An error occurred: {e!r}")
                    raise
            if self._cancelled is not None:
                if exceptions := [e for pen in self._failed if isinstance(e := pen.exception(), Exception)]:
                    msg = f"One or more exceptions occurred in this context! {list(map(str, exceptions))}"
                    raise ExceptionGroup(msg, exceptions)
                if self._mode in [0, 1]:
                    raise PendingCancelled(self._cancelled)
        finally:
            self._leaving_context = True
            self._deactivate(token)
            self._instances.pop(self.id, None)
            if self._pending:
                if self._all_done or self._all_done.cancelled():
                    self._all_done = create_async_event()
                if self._pending and not self._all_done:
                    with anyio.CancelScope(shield=True), anyio.move_on_after(self.cancellation_timeout):
                        await self._all_done

    @override
    def add(self, pen: Pending) -> None:
        if pen not in self._pending:
            self._pending.add(pen)
            pen.add_done_callback(self._on_pending_done)
        if (id_ := self._parent_id) and (parent := self._instances.get(id_)):
            parent.add(pen)

    @override
    def _on_pending_done(self, pen: Pending) -> None:
        try:
            self._pending.remove(pen)
            if pen.cancelled():
                if self._mode in [1, 2]:
                    self.cancel(f"A monitored pending was cancelled {pen=}")
            elif pen.exception():
                self._failed.append(pen)
                self.cancel(f"Exception in member: {pen}")
        except KeyError:
            pass
        if self._leaving_context and not self._pending:
            self._all_done.set()

    def cancel(self, msg: str | None = None) -> bool:
        "Cancel the pending group (internally synchronised)."
        self._cancelled = "\n".join(((self._cancelled or ""), msg or ""))
        if not self._cancel_scope.cancel_called:
            self.caller.call_direct(self._cancel_scope.cancel, msg)
            for pen_ in self.pending:
                pen_.cancel(msg)
        return self.cancelled()

    def cancelled(self) -> bool:
        """Returns: If the pending group is marked as cancelled."""
        return self._cancelled is not None

cancellation_timeout class-attribute instance-attribute

cancellation_timeout = 10

The maximum time to wait for cancelled pending to be done.

caller class-attribute instance-attribute

caller: Fixed[Self, Caller] = Fixed(lambda _: Caller())

The caller where the pending group was instantiated.

__init__

__init__(*, shield: bool = False, mode: int = 0) -> None

The pending group will only exit once all pending in the group are done.

Pending can be added to and removed from the group manually.

Parameters:

  • shield

    (bool, default: False ) –

    Passed to the cancel scope.

  • mode

    (int, default: 0 ) –

    The mode. - 0: Ignore cancellation of pending. - 1: Cancel if any pending is cancelled - raise PendingCancelled on exit. - 2: Cancel if any pending is cancelled - exit quietly.

Source code in src/async_kernel/pending.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def __init__(self, *, shield: bool = False, mode: int = 0) -> None:
    """
    An async context to capture all pending (that opt in) created in the context.

    The pending group will only exit once all pending in the group are `done`.

    Pending can be added to and removed from the group manually.

    Args:
        shield: Passed to the cancel scope.
        mode: The mode.
            - 0: Ignore cancellation of pending.
            - 1: Cancel if any pending is cancelled - raise PendingCancelled on exit.
            - 2: Cancel if any pending is cancelled - exit quietly.
    """
    assert mode in [0, 1, 2]
    self._mode = mode
    self._shield = shield
    self.caller  # noqa: B018
    super().__init__()

cancel

cancel(msg: str | None = None) -> bool

Cancel the pending group (internally synchronised).

Source code in src/async_kernel/pending.py
295
296
297
298
299
300
301
302
def cancel(self, msg: str | None = None) -> bool:
    "Cancel the pending group (internally synchronised)."
    self._cancelled = "\n".join(((self._cancelled or ""), msg or ""))
    if not self._cancel_scope.cancel_called:
        self.caller.call_direct(self._cancel_scope.cancel, msg)
        for pen_ in self.pending:
            pen_.cancel(msg)
    return self.cancelled()

cancelled

cancelled() -> bool

Returns: If the pending group is marked as cancelled.

Source code in src/async_kernel/pending.py
304
305
306
def cancelled(self) -> bool:
    """Returns: If the pending group is marked as cancelled."""
    return self._cancelled is not None

Pending

Bases: Awaitable[T]

Pending is an internally synchronised, cancellable, awaitable class influenced by asyncio.Future.

  • It can be wait/awaited and cancelled from any thread (not considering deadlocks)
  • Provides metadata storage
  • Has built in support for tracking pending created in a specific context (see: PendingManager and PendingGroup).

Properties

High level methods

Low level methods

Methods:

  • __init__

    Initializes a new pending object with optional creation options and metadata.

  • wait

    Wait for result or exception to be set (internally synchronised) returning the result if specified.

  • wait_sync

    Wait synchronously for result or exception (internally synchronised) returning the result if specified.

  • set_result

    Set the result (low-level internally synchronised).

  • set_exception

    Set the exception (low-level internally synchronised).

  • cancel

    Cancel the pending if it is not already done.

  • cancel_wait

    Cancel the pending and wait for it to be done.

  • cancelled

    Returns:

  • set_canceller

    Set a callback to handle cancellation (low-level).

  • done

    Returns True if a result or exception has been set.

  • add_done_callback

    Add a callback for when the pending is done.

  • remove_done_callback

    Remove fn from the done callback list.

  • result

    Return the result.

  • exception

    Return the exception.

Attributes:

Source code in src/async_kernel/pending.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
class Pending(Awaitable[T]):
    """
    Pending is an internally synchronised, cancellable, awaitable class influenced by [asyncio.Future][].

    - It can be wait/awaited and cancelled from any thread (not considering deadlocks)
    - Provides metadata storage
    - Has built in support for tracking pending created in a specific context (see: [PendingManager][] and [PendingGroup][]).

    **Properties**

    - [Pending.metadata][]: Metadata associated with the pending.
    - [Pending.context][]: The context associated with the pending.

    **High level methods**

    - [Pending.wait][]: Wait asynchronously for the pending to be complete.
    - [Pending.wait_sync][]: Wait synchronously for the pending to be complete.
    - [Pending.cancel][]: Cancel the pending (result must be set to finalize cancellation).
    - [Pending.result][]: Get the result of the pending.
    - [Pending.exception][]: Get the exception of the pending.

    **Low level methods**

    - [Pending.add_done_callback][]: Add a callback that is called once the pending is complete.
    - [Pending.remove_done_callback][]: Remove a previously added callback.
    - [Pending.set_canceller][]: Set a callback to handle cancellation.
    """

    __slots__ = [
        "__weakref__",
        "_cancelled",
        "_canceller",
        "_done",
        "_done_callbacks",
        "_exception",
        "_result",
        "_waiting",
        "context",
    ]

    _REPR_OMIT: ClassVar[list[str]] = ["func", "args", "kwargs", "caller"]
    "Keys of metadata to omit when creating a repr of the pending."

    _metadata_mappings: ClassVar[dict[int, dict[str, Any]]] = {}
    "A mapping of pending ids to metadata."

    _cancelled: str | None
    _canceller: Callable[[str | None], Any] | None
    _exception: Exception
    _done: bool
    _result: T
    context: contextvars.Context | None
    """The context associated with Pending."""

    @property
    def metadata(self) -> dict[str, Any]:
        """
        The metadata associated with the pending.
        """
        return self._metadata_mappings[id(self)]

    def __init__(
        self,
        context: contextvars.Context | None = None,
        trackers: type[PendingTracker] | tuple[type[PendingTracker], ...] = (),
        /,
        **metadata: Any,
    ) -> None:
        """
        Initializes a new pending object with optional creation options and metadata.

        Args:
            context: A context to associate with the pending, if provided it is copied.
            trackers: A subclass or tuple of `PendingTracker` subclasses to which the pending can be added in the current context.
            **metadata: Arbitrary keyword arguments containing metadata to associate with this Pending instance.

        Behavior:
            - Initializes internal state for tracking completion and cancellation.
            - Stores provided metadata in a class-level mapping.
        """
        self._done_callbacks: list[Callable[[Self], Any]] = []
        self._metadata_mappings[id(self)] = metadata
        self._done = False
        self._cancelled = None
        self._canceller = None

        if trackers or context:
            # A copy the context is required to avoid `PendingTracker.id` leakage.
            context = context.copy() if context else contextvars.copy_context()
        self.context = context

        # PendingTacker registration.
        if context:
            for cls in PendingTracker._subclasses:  # pyright: ignore[reportPrivateUsage]
                if id_ := context.get(cls._id_contextvar):  # pyright: ignore[reportPrivateUsage]
                    if trackers and issubclass(cls, trackers) and (tracker := PendingTracker._instances.get(id_)):  # pyright: ignore[reportPrivateUsage]
                        tracker.add(self)
                    else:
                        # Clear `PendingTracker.id`.
                        context.run(cls._id_contextvar.set, None)  # pyright: ignore[reportPrivateUsage]

    def __del__(self) -> None:
        self._metadata_mappings.pop(id(self), None)

    @override
    def __repr__(self) -> str:
        rep = (
            "<Pending"
            + ((" ⛔" + (f"message={self._cancelled!s}" if self._cancelled else "")) if self.cancelled() else "")
            + ((f" ❗ {e!r}" if (e := getattr(self, "_exception", None)) else " 🏁") if self._done else " 🏃")
        )
        rep = f"{rep} at {id(self)}"
        with contextlib.suppress(Exception):
            if md := self.metadata:
                rep = f"{rep} metadata:"
                if "func" in md:
                    items = [f"{k}={truncated_rep.repr(v)}" for k, v in md.items() if k not in self._REPR_OMIT]
                    rep += f" | {md['func']} {' | '.join(items) if items else ''}"
                else:
                    rep += f"{truncated_rep.repr(md)}"
        return rep + " >"

    @override
    def __await__(self) -> Generator[Any, None, T]:
        return self.wait().__await__()

    if TYPE_CHECKING:

        @overload
        async def wait(
            self, *, timeout: float | None = ..., protect: bool = False | ..., result: Literal[True] = True
        ) -> T: ...

        @overload
        async def wait(self, *, timeout: float | None = ..., protect: bool = ..., result: Literal[False]) -> None: ...

    async def wait(self, *, timeout: float | None = None, protect: bool = False, result: bool = True) -> T | None:
        """
        Wait for `result` or `exception` to be set (internally synchronised) returning the result if specified.

        Args:
            timeout: Timeout in seconds.
            protect: Protect the pending from a `TimeoutError` or external cancellation.
            result: If `result` should be returned.

        Raises:
            TimeoutError: When the timeout expires and a result or exception has not been set.
            PendingCancelled: If `result=True` and the pending has been cancelled.
            Exception: If `result=True` and an exception was set on the pending.

        Tip:
            To wait for a cancelled pending to complete use `await pen.wait(result=False)`.
        """
        try:
            if not self._done or self._done_callbacks:
                waiter = create_async_waiter()
                self.add_done_callback(lambda _: waiter.wake())
                if timeout is None:
                    await waiter
                else:
                    with anyio.fail_after(timeout):
                        await waiter
            return self.result() if result else None
        except (anyio.get_cancelled_exc_class(), TimeoutError) as e:
            if not protect:
                self.cancel(f"Cancelled due to cancellation or timeout: {e}.")
            raise

    if TYPE_CHECKING:

        @overload
        def wait_sync(
            self, *, timeout: float | None = ..., protect: bool = False | ..., result: Literal[True] = True
        ) -> T: ...

        @overload
        def wait_sync(self, *, timeout: float | None = ..., protect: bool = ..., result: Literal[False]) -> None: ...

    def wait_sync(self, *, timeout: float | None = None, protect: bool = False, result: bool = True) -> T | None:
        """
        Wait synchronously for `result` or `exception` (internally synchronised) returning the result if specified.

        Args:
            timeout: Timeout in seconds.
            protect: Protect the pending from cancellation from a `TimeoutError`.
            result: When `True` the result is returned.

        Raises:
            TimeoutError: When the timeout expires and a result or exception has not been set.
            PendingCancelled: If `result=True` and the pending has been cancelled.
            Exception: If `result=True` and an exception was set on the pending.

        Warning:
            **Calling this method in the same thread where the result or exception is set
            will result in deadlock unless a greenlet based event library is in use.**
        """
        if not self._done or self._done_callbacks:
            event = Event()
            self.add_done_callback(lambda _: event.set())
            event.wait(timeout)
            if not self._done:
                msg = f"Timeout waiting for {self}"
                if not protect:
                    self.cancel(msg)
                raise TimeoutError(msg)
        return self.result() if result else None

    def _set_done(self, mode: Literal["result", "exception"], value: T | BaseException | None) -> None:
        if self._done:
            raise InvalidStateError
        self._done = True
        e = None
        self._canceller = None
        # List reversal and BaseException handling inspiration: https://gist.github.com/x42005e1f/4f18c3c62da9135020bdea8c44c248a2
        callbacks = self._done_callbacks
        callbacks.reverse()
        if not self._cancelled:
            setattr(self, "_" + mode, value)
        while callbacks:
            try:
                callbacks.pop()(self)
            except Exception:
                pass
            except BaseException as exc:
                e = exc
        if e:
            raise e from None

    def set_result(self, value: T) -> None:
        """
        Set the result (low-level internally synchronised).

        Args:
            value: The result to set.

        Raises:
            InvalidStateError: If the pending is already done.
        """
        self._set_done("result", value)

    def set_exception(self, exception: BaseException) -> None:
        """
        Set the exception (low-level internally synchronised).

        Args:
            exception: The value to set as the exception.

        Raises:
            InvalidStateError: If the pending is already done.
        """
        self._set_done("exception", exception)

    def cancel(self, msg: str | None = None) -> bool:
        """
        Cancel the pending if it is not already `done`.

        Args:
            msg: The cancellation message.

        Returns:
            If the pending is marked as cancelled.

        Notes:
            - Cancellation cannot be undone.
            - Multiple calls append `msg` to the cancellation message with no other effect.
            - The `done` state is a function of the canceller, if no canceller is set, `done`
                will be set immediately.
        """
        if not self._done:
            if (cancelled := self._cancelled or "") and msg:
                msg = f"{cancelled}\n{msg}"
            self._cancelled = msg or cancelled
            if not (canceller := self._canceller):
                try:
                    self._set_done("result", None)
                except InvalidStateError:
                    pass
            else:
                canceller(msg)
        return self._cancelled is not None

    async def cancel_wait(self, msg: str | None, *, timeout: float | None = None) -> None:
        "Cancel the pending and wait for it to be `done`."
        if not self._done:
            self.cancel(msg)
            if not self._done:
                await self.wait(result=False, timeout=timeout)

    def cancelled(self) -> bool:
        """
        Returns:
            If the pending is marked as cancelled.

        Notes:

            - This can return `True` before a pending is `done`.
            - To wait for a pending to complete (assuming a canceller is or will be set); use
                `await pen.wait(result=False)` or `pen.wait_sync(result=False)`
        """
        return self._cancelled is not None

    def set_canceller(self, canceller: Callable[[str | None], Any], /) -> None:
        """
        Set a callback to handle cancellation (low-level).

        Args:
            canceller: A callback that performs the cancellation of the pending.

                - It must accept the cancellation message as the first argument.
                - `canceller` must be externally synchronised.

        Warning:
            - [set_result][] or [set_exception][] *MUST* be called by the `canceller`, or as a result of the call to `canceller`
                to mark the pending as `done`.

        Raises:
            InvalidStateError: If already `done`.
            PendingCancelled: If already `cancelled`.

        Example:
            ```python
            pen = Pending()
            pen.cancel()
            assert not pen.done()
            pen.set_canceller(lambda msg: pen.set_result(None))
            assert pen.done()
            ```
        """
        if self._done:
            if self._cancelled is not None:
                raise PendingCancelled(self._cancelled)
            raise InvalidStateError
        self._canceller = canceller

    def done(self) -> bool:
        """
        Returns `True` if a result or exception has been set.
        """
        return self._done

    def add_done_callback(self, fn: Callable[[Self], Any], /) -> None:
        """
        Add a callback for when the pending is `done`.

        The callback should be light weight and provide its own thread safety.

        Callbacks added are handled FIFO.
        """
        if not self._done:
            self._done_callbacks.append(fn)
        elif self._done_callbacks:
            # respect FIFO - 'done_callbacks' gets reversed in `_set_done`.
            self._done_callbacks.insert(0, fn)
        else:
            fn(self)

    def remove_done_callback(self, fn: Callable[[Self], object], /) -> int:
        """
        Remove `fn` from the done callback list.

        Returns the number of items removed.
        """
        n = 0
        while fn in self._done_callbacks:
            n += 1
            self._done_callbacks.remove(fn)
        return n

    def result(self) -> T:
        """
        Return the result.

        Raises:
            PendingCancelled: If the pending has been cancelled.
            InvalidStateError: If the pending isn't done yet.
        """
        if e := self.exception():
            raise e from None
        try:
            return self._result
        except AttributeError:
            raise InvalidStateError from None

    def exception(self) -> BaseException | None:
        """
        Return the exception.

        Raises:
            PendingCancelled: If the pending has been cancelled.
        """
        if self._cancelled is not None:
            raise PendingCancelled(self._cancelled)
        return getattr(self, "_exception", None)

metadata property

metadata: dict[str, Any]

The metadata associated with the pending.

context instance-attribute

context: Context | None = context

The context associated with Pending.

__init__

__init__(
    context: Context | None = None,
    trackers: type[PendingTracker] | tuple[type[PendingTracker], ...] = (),
    /,
    **metadata: Any,
) -> None

Parameters:

  • context

    (Context | None, default: None ) –

    A context to associate with the pending, if provided it is copied.

  • trackers

    (type[PendingTracker] | tuple[type[PendingTracker], ...], default: () ) –

    A subclass or tuple of PendingTracker subclasses to which the pending can be added in the current context.

  • **metadata

    (Any, default: {} ) –

    Arbitrary keyword arguments containing metadata to associate with this Pending instance.

Behavior
  • Initializes internal state for tracking completion and cancellation.
  • Stores provided metadata in a class-level mapping.
Source code in src/async_kernel/pending.py
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
408
def __init__(
    self,
    context: contextvars.Context | None = None,
    trackers: type[PendingTracker] | tuple[type[PendingTracker], ...] = (),
    /,
    **metadata: Any,
) -> None:
    """
    Initializes a new pending object with optional creation options and metadata.

    Args:
        context: A context to associate with the pending, if provided it is copied.
        trackers: A subclass or tuple of `PendingTracker` subclasses to which the pending can be added in the current context.
        **metadata: Arbitrary keyword arguments containing metadata to associate with this Pending instance.

    Behavior:
        - Initializes internal state for tracking completion and cancellation.
        - Stores provided metadata in a class-level mapping.
    """
    self._done_callbacks: list[Callable[[Self], Any]] = []
    self._metadata_mappings[id(self)] = metadata
    self._done = False
    self._cancelled = None
    self._canceller = None

    if trackers or context:
        # A copy the context is required to avoid `PendingTracker.id` leakage.
        context = context.copy() if context else contextvars.copy_context()
    self.context = context

    # PendingTacker registration.
    if context:
        for cls in PendingTracker._subclasses:  # pyright: ignore[reportPrivateUsage]
            if id_ := context.get(cls._id_contextvar):  # pyright: ignore[reportPrivateUsage]
                if trackers and issubclass(cls, trackers) and (tracker := PendingTracker._instances.get(id_)):  # pyright: ignore[reportPrivateUsage]
                    tracker.add(self)
                else:
                    # Clear `PendingTracker.id`.
                    context.run(cls._id_contextvar.set, None)  # pyright: ignore[reportPrivateUsage]

wait async

wait(
    *,
    timeout: float | None = ...,
    protect: bool = False | ...,
    result: Literal[True] = True,
) -> T
wait(*, timeout: float | None = ..., protect: bool = ..., result: Literal[False]) -> None
wait(
    *, timeout: float | None = None, protect: bool = False, result: bool = True
) -> T | None

Wait for result or exception to be set (internally synchronised) returning the result if specified.

Parameters:

  • timeout

    (float | None, default: None ) –

    Timeout in seconds.

  • protect

    (bool, default: False ) –

    Protect the pending from a TimeoutError or external cancellation.

  • result

    (bool, default: True ) –

    If result should be returned.

Raises:

  • TimeoutError

    When the timeout expires and a result or exception has not been set.

  • PendingCancelled

    If result=True and the pending has been cancelled.

  • Exception

    If result=True and an exception was set on the pending.

Tip

To wait for a cancelled pending to complete use await pen.wait(result=False).

Source code in src/async_kernel/pending.py
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
async def wait(self, *, timeout: float | None = None, protect: bool = False, result: bool = True) -> T | None:
    """
    Wait for `result` or `exception` to be set (internally synchronised) returning the result if specified.

    Args:
        timeout: Timeout in seconds.
        protect: Protect the pending from a `TimeoutError` or external cancellation.
        result: If `result` should be returned.

    Raises:
        TimeoutError: When the timeout expires and a result or exception has not been set.
        PendingCancelled: If `result=True` and the pending has been cancelled.
        Exception: If `result=True` and an exception was set on the pending.

    Tip:
        To wait for a cancelled pending to complete use `await pen.wait(result=False)`.
    """
    try:
        if not self._done or self._done_callbacks:
            waiter = create_async_waiter()
            self.add_done_callback(lambda _: waiter.wake())
            if timeout is None:
                await waiter
            else:
                with anyio.fail_after(timeout):
                    await waiter
        return self.result() if result else None
    except (anyio.get_cancelled_exc_class(), TimeoutError) as e:
        if not protect:
            self.cancel(f"Cancelled due to cancellation or timeout: {e}.")
        raise

wait_sync

wait_sync(
    *,
    timeout: float | None = ...,
    protect: bool = False | ...,
    result: Literal[True] = True,
) -> T
wait_sync(
    *, timeout: float | None = ..., protect: bool = ..., result: Literal[False]
) -> None
wait_sync(
    *, timeout: float | None = None, protect: bool = False, result: bool = True
) -> T | None

Wait synchronously for result or exception (internally synchronised) returning the result if specified.

Parameters:

  • timeout

    (float | None, default: None ) –

    Timeout in seconds.

  • protect

    (bool, default: False ) –

    Protect the pending from cancellation from a TimeoutError.

  • result

    (bool, default: True ) –

    When True the result is returned.

Raises:

  • TimeoutError

    When the timeout expires and a result or exception has not been set.

  • PendingCancelled

    If result=True and the pending has been cancelled.

  • Exception

    If result=True and an exception was set on the pending.

Warning

Calling this method in the same thread where the result or exception is set will result in deadlock unless a greenlet based event library is in use.

Source code in src/async_kernel/pending.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def wait_sync(self, *, timeout: float | None = None, protect: bool = False, result: bool = True) -> T | None:
    """
    Wait synchronously for `result` or `exception` (internally synchronised) returning the result if specified.

    Args:
        timeout: Timeout in seconds.
        protect: Protect the pending from cancellation from a `TimeoutError`.
        result: When `True` the result is returned.

    Raises:
        TimeoutError: When the timeout expires and a result or exception has not been set.
        PendingCancelled: If `result=True` and the pending has been cancelled.
        Exception: If `result=True` and an exception was set on the pending.

    Warning:
        **Calling this method in the same thread where the result or exception is set
        will result in deadlock unless a greenlet based event library is in use.**
    """
    if not self._done or self._done_callbacks:
        event = Event()
        self.add_done_callback(lambda _: event.set())
        event.wait(timeout)
        if not self._done:
            msg = f"Timeout waiting for {self}"
            if not protect:
                self.cancel(msg)
            raise TimeoutError(msg)
    return self.result() if result else None

set_result

set_result(value: T) -> None

Set the result (low-level internally synchronised).

Parameters:

  • value

    (T) –

    The result to set.

Raises:

Source code in src/async_kernel/pending.py
537
538
539
540
541
542
543
544
545
546
547
def set_result(self, value: T) -> None:
    """
    Set the result (low-level internally synchronised).

    Args:
        value: The result to set.

    Raises:
        InvalidStateError: If the pending is already done.
    """
    self._set_done("result", value)

set_exception

set_exception(exception: BaseException) -> None

Set the exception (low-level internally synchronised).

Parameters:

Raises:

Source code in src/async_kernel/pending.py
549
550
551
552
553
554
555
556
557
558
559
def set_exception(self, exception: BaseException) -> None:
    """
    Set the exception (low-level internally synchronised).

    Args:
        exception: The value to set as the exception.

    Raises:
        InvalidStateError: If the pending is already done.
    """
    self._set_done("exception", exception)

cancel

cancel(msg: str | None = None) -> bool

Cancel the pending if it is not already done.

Parameters:

  • msg

    (str | None, default: None ) –

    The cancellation message.

Returns:

  • bool

    If the pending is marked as cancelled.

Notes
  • Cancellation cannot be undone.
  • Multiple calls append msg to the cancellation message with no other effect.
  • The done state is a function of the canceller, if no canceller is set, done will be set immediately.
Source code in src/async_kernel/pending.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def cancel(self, msg: str | None = None) -> bool:
    """
    Cancel the pending if it is not already `done`.

    Args:
        msg: The cancellation message.

    Returns:
        If the pending is marked as cancelled.

    Notes:
        - Cancellation cannot be undone.
        - Multiple calls append `msg` to the cancellation message with no other effect.
        - The `done` state is a function of the canceller, if no canceller is set, `done`
            will be set immediately.
    """
    if not self._done:
        if (cancelled := self._cancelled or "") and msg:
            msg = f"{cancelled}\n{msg}"
        self._cancelled = msg or cancelled
        if not (canceller := self._canceller):
            try:
                self._set_done("result", None)
            except InvalidStateError:
                pass
        else:
            canceller(msg)
    return self._cancelled is not None

cancel_wait async

cancel_wait(msg: str | None, *, timeout: float | None = None) -> None

Cancel the pending and wait for it to be done.

Source code in src/async_kernel/pending.py
590
591
592
593
594
595
async def cancel_wait(self, msg: str | None, *, timeout: float | None = None) -> None:
    "Cancel the pending and wait for it to be `done`."
    if not self._done:
        self.cancel(msg)
        if not self._done:
            await self.wait(result=False, timeout=timeout)

cancelled

cancelled() -> bool

Returns:

  • bool

    If the pending is marked as cancelled.

Notes:

- This can return `True` before a pending is `done`.
- To wait for a pending to complete (assuming a canceller is or will be set); use
    `await pen.wait(result=False)` or `pen.wait_sync(result=False)`
Source code in src/async_kernel/pending.py
597
598
599
600
601
602
603
604
605
606
607
608
def cancelled(self) -> bool:
    """
    Returns:
        If the pending is marked as cancelled.

    Notes:

        - This can return `True` before a pending is `done`.
        - To wait for a pending to complete (assuming a canceller is or will be set); use
            `await pen.wait(result=False)` or `pen.wait_sync(result=False)`
    """
    return self._cancelled is not None

set_canceller

set_canceller(canceller: Callable[[str | None], Any]) -> None

Set a callback to handle cancellation (low-level).

Parameters:

  • canceller

    (Callable[[str | None], Any]) –

    A callback that performs the cancellation of the pending.

    • It must accept the cancellation message as the first argument.
    • canceller must be externally synchronised.
Warning
  • set_result or set_exception MUST be called by the canceller, or as a result of the call to canceller to mark the pending as done.

Raises:

Example
pen = Pending()
pen.cancel()
assert not pen.done()
pen.set_canceller(lambda msg: pen.set_result(None))
assert pen.done()
Source code in src/async_kernel/pending.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def set_canceller(self, canceller: Callable[[str | None], Any], /) -> None:
    """
    Set a callback to handle cancellation (low-level).

    Args:
        canceller: A callback that performs the cancellation of the pending.

            - It must accept the cancellation message as the first argument.
            - `canceller` must be externally synchronised.

    Warning:
        - [set_result][] or [set_exception][] *MUST* be called by the `canceller`, or as a result of the call to `canceller`
            to mark the pending as `done`.

    Raises:
        InvalidStateError: If already `done`.
        PendingCancelled: If already `cancelled`.

    Example:
        ```python
        pen = Pending()
        pen.cancel()
        assert not pen.done()
        pen.set_canceller(lambda msg: pen.set_result(None))
        assert pen.done()
        ```
    """
    if self._done:
        if self._cancelled is not None:
            raise PendingCancelled(self._cancelled)
        raise InvalidStateError
    self._canceller = canceller

done

done() -> bool

Returns True if a result or exception has been set.

Source code in src/async_kernel/pending.py
643
644
645
646
647
def done(self) -> bool:
    """
    Returns `True` if a result or exception has been set.
    """
    return self._done

add_done_callback

add_done_callback(fn: Callable[[Self], Any]) -> None

Add a callback for when the pending is done.

The callback should be light weight and provide its own thread safety.

Callbacks added are handled FIFO.

Source code in src/async_kernel/pending.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def add_done_callback(self, fn: Callable[[Self], Any], /) -> None:
    """
    Add a callback for when the pending is `done`.

    The callback should be light weight and provide its own thread safety.

    Callbacks added are handled FIFO.
    """
    if not self._done:
        self._done_callbacks.append(fn)
    elif self._done_callbacks:
        # respect FIFO - 'done_callbacks' gets reversed in `_set_done`.
        self._done_callbacks.insert(0, fn)
    else:
        fn(self)

remove_done_callback

remove_done_callback(fn: Callable[[Self], object]) -> int

Remove fn from the done callback list.

Returns the number of items removed.

Source code in src/async_kernel/pending.py
665
666
667
668
669
670
671
672
673
674
675
def remove_done_callback(self, fn: Callable[[Self], object], /) -> int:
    """
    Remove `fn` from the done callback list.

    Returns the number of items removed.
    """
    n = 0
    while fn in self._done_callbacks:
        n += 1
        self._done_callbacks.remove(fn)
    return n

result

result() -> T

Return the result.

Raises:

Source code in src/async_kernel/pending.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def result(self) -> T:
    """
    Return the result.

    Raises:
        PendingCancelled: If the pending has been cancelled.
        InvalidStateError: If the pending isn't done yet.
    """
    if e := self.exception():
        raise e from None
    try:
        return self._result
    except AttributeError:
        raise InvalidStateError from None

exception

exception() -> BaseException | None

Return the exception.

Raises:

Source code in src/async_kernel/pending.py
692
693
694
695
696
697
698
699
700
701
def exception(self) -> BaseException | None:
    """
    Return the exception.

    Raises:
        PendingCancelled: If the pending has been cancelled.
    """
    if self._cancelled is not None:
        raise PendingCancelled(self._cancelled)
    return getattr(self, "_exception", None)