caller
Classes:
-
PendingGroup–An asynchronous context manager that automatically registers pending created in its context.
-
Caller–Caller is an advanced asynchronous context manager and scheduler for managing function calls within an async kernel environment.
PendingGroup
¶
Bases: PendingTracker, AsyncContextManagerMixin
An asynchronous context manager that automatically registers pending created in its context.
Any pending created within the context (except those that explicitly opt-out) are automatically added to the group.
If any pending fails, is cancelled (with the result/exception set) or the pending group is cancelled; the context will exit, and all pending will be cancelled.
Features
- The context will exit after all tracked pending are done or removed.
- Cancelled or failed pending will cancel all other pending in the group.
- Pending can be manually removed from the group while the group is active.
Parameters:
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:
-
remove–Remove pen from the group.
-
cancel–Cancel the pending group (thread-safe).
-
cancelled–Return True if the pending group is cancelled.
Source code in src/async_kernel/pending.py
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 | |
remove
¶
remove(pen: Pending) -> None
Remove pen from the group.
Source code in src/async_kernel/pending.py
549 550 551 552 553 554 555 556 557 | |
cancel
¶
cancel(msg: str | None = None) -> None
Cancel the pending group (thread-safe).
Source code in src/async_kernel/pending.py
559 560 561 562 563 | |
Caller
¶
Bases: AsyncContextManagerMixin
Caller is an advanced asynchronous context manager and scheduler for managing function calls within an async kernel environment.
Features
- Manages a pool of worker threads and async contexts for efficient scheduling and execution.
- Supports synchronous and asynchronous startup, shutdown, and cleanup of idle workers.
- Provides thread-safe scheduling of functions (sync/async), with support for delayed and queued execution.
- Integrates with ZeroMQ (zmq) for PUB socket communication.
- Tracks child caller instances, enabling hierarchical shutdown and resource management.
- Offers mechanisms for direct calls, queued calls, and thread offloading.
- Implements
as_completedandwaitutilities for monitoring and collecting results from scheduled tasks. - Handles cancellation, exceptions, and context propagation robustly.
Usage
- Use Caller to manage async/sync function execution, worker threads, and task scheduling in complex async applications.
- Integrate with ZeroMQ for PUB socket communication.
- Leverage child management for hierarchical resource cleanup.
- Use
as_completedandwaitfor efficient result collection and monitoring.
-
Reference
caller
Callerall_callers
Methods:
-
__new__–Create or retrieve a Caller instance.
-
start_sync–Start synchronously.
-
stop–Stop the caller, cancelling all pending tasks and close the thread.
-
get_current–A classmethod to get the caller instance from the corresponding thread if it exists.
-
current_pending–A classmethod that returns the current result when called from inside a function scheduled by Caller.
-
all_callers–A classmethod to get a list of the callers.
-
get–Retrieves an existing child caller by name and backend, or creates a new one if not found.
-
schedule_call–Schedule
functo be called inside a task running in the callers thread (thread-safe). -
call_later–Schedule func to be called in caller's event loop copying the current context.
-
call_soon–Schedule func to be called in caller's event loop copying the current context.
-
call_direct–Schedule
functo be called in caller's event loop directly. -
to_thread–Call func in a worker thread using the same backend as the current instance.
-
queue_get–Returns
Pendinginstance forfuncwhere the queue is running. -
queue_call–Queue the execution of
funcin a queue unique to it and the caller instance (thread-safe). -
queue_close–Close the execution queue associated with
func(thread-safe). -
as_completed–An iterator to get result as they complete.
-
wait–Wait for the results given by items to complete.
-
create_pending_group–Create a new pending group.
Attributes:
-
MAX_IDLE_POOL_INSTANCES–The number of
poolinstances to leave idle (See also to_thread). -
IDLE_WORKER_SHUTDOWN_DURATION–The minimum duration in seconds for a worker to remain in the worker pool before it is shutdown.
-
stopped–A thread-safe Event for when the caller is stopped.
-
log(LoggerAdapter[Any]) – -
iopub_sockets(dict[Thread, Socket]) – -
iopub_url(ClassVar) – -
name(str) –The name of the thread when the caller was created.
-
thread(Thread) –The thread in which the caller will run.
-
backend(Backend) –The
anyiobackend the caller is running in. -
protected(bool) –Returns
Trueif the caller is protected from stopping. -
zmq_context(Context | None) –A zmq socket, which if present indicates that an iopub socket is loaded.
-
running–Returns
Truewhen the caller is available to run requests. -
children(frozenset[Self]) –A frozenset copy of the instances that were created by the caller.
-
parent(Self | None) –The parent if it exists.
Source code in src/async_kernel/caller.py
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 101 102 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 179 180 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 307 308 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 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 | |
MAX_IDLE_POOL_INSTANCES
class-attribute
instance-attribute
¶
MAX_IDLE_POOL_INSTANCES = 10
The number of pool instances to leave idle (See also to_thread).
IDLE_WORKER_SHUTDOWN_DURATION
class-attribute
instance-attribute
¶
IDLE_WORKER_SHUTDOWN_DURATION = 0 if 'pytest' in modules else 60
The minimum duration in seconds for a worker to remain in the worker pool before it is shutdown.
Set to 0 to disable (default when running tests).
stopped
class-attribute
instance-attribute
¶
A thread-safe Event for when the caller is stopped.
zmq_context
property
¶
zmq_context: Context | None
A zmq socket, which if present indicates that an iopub socket is loaded.
children
property
¶
A frozenset copy of the instances that were created by the caller.
Notes
- When the parent is stopped, all children are stopped.
- All children are stopped prior to the parent exiting its async context.
__new__
¶
__new__(
modifier: Literal[
"CurrentThread", "MainThread", "NewThread", "manual"
] = "CurrentThread",
/,
**kwargs: Unpack[CallerCreateOptions],
) -> Self
Create or retrieve a Caller instance.
Parameters:
-
(modifier¶Literal['CurrentThread', 'MainThread', 'NewThread', 'manual'], default:'CurrentThread') –Specifies how the Caller instance should be created or retrieved.
- "CurrentThread": Automatically create or retrieve the instance.
- "MainThread": Use the main thread for the Caller.
- "NewThread": Create a new thread.
- "manual": Manually create a new instance for the current thread.
-
(**kwargs¶Unpack[CallerCreateOptions], default:{}) –Additional options for Caller creation, such as: - name: The name to use. - backend: The async backend to use. - backend_options: Options for the backend. - protected: Whether the Caller is protected. - zmq_context: ZeroMQ context. - log: Logger instance.
Returns:
-
Self(Self) –The created or retrieved Caller instance.
Raises:
-
RuntimeError–If the backend is not provided and backend can't be determined.
-
ValueError–If the thread and caller's name do not match.
Source code in src/async_kernel/caller.py
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 | |
start_sync
¶
start_sync() -> None
Start synchronously.
Source code in src/async_kernel/caller.py
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 | |
stop
¶
stop(*, force=False) -> CallerState
Stop the caller, cancelling all pending tasks and close the thread.
If the instance is protected, this is no-op unless force is used.
Source code in src/async_kernel/caller.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
get_current
classmethod
¶
A classmethod to get the caller instance from the corresponding thread if it exists.
Source code in src/async_kernel/caller.py
480 481 482 483 484 | |
current_pending
classmethod
¶
A classmethod that returns the current result when called from inside a function scheduled by Caller.
Source code in src/async_kernel/caller.py
486 487 488 489 | |
all_callers
classmethod
¶
A classmethod to get a list of the callers.
Parameters:
-
(running_only¶bool, default:True) –Restrict the list to callers that are active (running in an async context).
Source code in src/async_kernel/caller.py
491 492 493 494 495 496 497 498 499 | |
get
¶
get(**kwargs: Unpack[CallerCreateOptions]) -> Self
Retrieves an existing child caller by name and backend, or creates a new one if not found.
Parameters:
-
(**kwargs¶Unpack[CallerCreateOptions], default:{}) –Options for creating or retrieving a caller instance. - name: The name of the child caller to retrieve. - backend: The backend to match or assign to the caller. - backend_options: Options for the backend. - zmq_context: ZeroMQ context to use.
Returns:
-
Self(Self) –The retrieved or newly created caller instance.
Raises:
-
RuntimeError–If a caller with the specified name exists but the backend does not match.
Notes
- The returned caller is added to
childrenand stopped with this instance. - If 'backend' and 'zmq_context' are not specified they are copied from this instance.
- Usage Usage Caller Caller.get
Source code in src/async_kernel/caller.py
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 | |
schedule_call
¶
schedule_call(
func: Callable[..., CoroutineType[Any, Any, T] | T],
args: tuple,
kwargs: dict,
pending_create_options: PendingCreateOptions | None = None,
context: Context | None = None,
/,
**metadata: Any,
) -> Pending[T]
Schedule func to be called inside a task running in the callers thread (thread-safe).
The methods call_soon and call_later use this method in the background, they should be used in preference to this method since they provide type hinting for the arguments.
Parameters:
-
(func¶Callable[..., CoroutineType[Any, Any, T] | T]) –The function to be called. If it returns a coroutine, it will be awaited and its result will be returned.
-
(args¶tuple) –Arguments corresponding to in the call to
func. -
(kwargs¶dict) –Keyword arguments to use with in the call to
func. -
(pending_create_options¶PendingCreateOptions | None, default:None) –Options are passed to Pending.
-
(context¶Context | None, default:None) –The context to use, if not provided the current context is used.
-
(**metadata¶Any, default:{}) –Additional metadata to store in the instance.
Source code in src/async_kernel/caller.py
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 | |
call_later
¶
call_later(
delay: float,
func: Callable[P, T | CoroutineType[Any, Any, T]],
/,
*args: args,
**kwargs: kwargs,
) -> Pending[T]
Schedule func to be called in caller's event loop copying the current context.
Parameters:
-
(func¶Callable[P, T | CoroutineType[Any, Any, T]]) –The function.
-
(delay¶float) –The minimum delay to add between submission and execution.
-
(*args¶args, default:()) –Arguments to use with func.
-
(**kwargs¶kwargs, default:{}) –Keyword arguments to use with func.
Info
All call arguments are packed into the instance's metadata.
-
Reference
caller
Callerschedule_call
Source code in src/async_kernel/caller.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 | |
call_soon
¶
call_soon(
func: Callable[P, T | CoroutineType[Any, Any, T]], /, *args: args, **kwargs: kwargs
) -> Pending[T]
Schedule func to be called in caller's event loop copying the current context.
Parameters:
-
(func¶Callable[P, T | CoroutineType[Any, Any, T]]) –The function.
-
(*args¶args, default:()) –Arguments to use with func.
-
(**kwargs¶kwargs, default:{}) –Keyword arguments to use with func.
Source code in src/async_kernel/caller.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | |
call_direct
¶
call_direct(
func: Callable[P, T | CoroutineType[Any, Any, T]], /, *args: args, **kwargs: kwargs
) -> None
Schedule func to be called in caller's event loop directly.
This method is provided to facilitate lightweight thread-safe function calls that need to be performed from within the callers event loop/taskgroup.
Parameters:
-
(func¶Callable[P, T | CoroutineType[Any, Any, T]]) –The function.
-
(*args¶args, default:()) –Arguments to use with func.
-
(**kwargs¶kwargs, default:{}) –Keyword arguments to use with func.
Warning:
**Use this method for lightweight calls only!**
Source code in src/async_kernel/caller.py
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 | |
to_thread
¶
to_thread(
func: Callable[P, T | CoroutineType[Any, Any, T]], /, *args: args, **kwargs: kwargs
) -> Pending[T]
Call func in a worker thread using the same backend as the current instance.
Parameters:
-
(func¶Callable[P, T | CoroutineType[Any, Any, T]]) –The function.
-
(*args¶args, default:()) –Arguments to use with func.
-
(**kwargs¶kwargs, default:{}) –Keyword arguments to use with func.
Notes
- A minimum number of caller instances are retained for this method.
- Async code run inside func should use taskgroups for creating task.
Source code in src/async_kernel/caller.py
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 | |
queue_get
¶
Returns Pending instance for func where the queue is running.
Warning
- This instance loops until the instance is closed or func is garbage collected.
- The pending has been modified such that waiting it will wait for the queue to be empty.
queue_closeis the preferred means to shutdown the queue.
Source code in src/async_kernel/caller.py
677 678 679 680 681 682 683 684 685 | |
queue_call
¶
queue_call(
func: Callable[P, T | CoroutineType[Any, Any, T]], /, *args: args, **kwargs: kwargs
) -> Pending[T]
Queue the execution of func in a queue unique to it and the caller instance (thread-safe).
Parameters:
-
(func¶Callable[P, T | CoroutineType[Any, Any, T]]) –The function.
-
(*args¶args, default:()) –Arguments to use with
func. -
(**kwargs¶kwargs, default:{}) –Keyword arguments to use with
func.
Warning
- Do not assume the result matches the function call.
- The returned pending returns the last result of the queue call once the queue becomes empty.
Notes
- The queue runs in a task wrapped with a async_kernel.pending.Pending that remains running until one of the following occurs:
- The pending is cancelled.
- The method Caller.queue_close is called with
funcorfunc's hash. funcis deleted (utilising weakref.finalize).
- The context of the initial call is used for subsequent queue calls.
- Exceptions are 'swallowed'; the last successful result is set on the pending.
Returns:
-
Pending(Pending[T]) –The pending where the queue loop is running.
Source code in src/async_kernel/caller.py
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 | |
queue_close
¶
Close the execution queue associated with func (thread-safe).
Parameters:
-
Reference
caller
Callerqueue_call
Source code in src/async_kernel/caller.py
757 758 759 760 761 762 763 764 765 766 | |
as_completed
async
¶
as_completed(
items: Iterable[Awaitable[T]] | AsyncGenerator[Awaitable[T]],
*,
max_concurrent: NoValue | int = NoValue,
cancel_unfinished: bool = True,
) -> AsyncGenerator[Pending[T], Any]
An iterator to get result as they complete.
Parameters:
-
(items¶Iterable[Awaitable[T]] | AsyncGenerator[Awaitable[T]]) –Either a container with existing results or generator of Pendings.
-
(max_concurrent¶NoValue | int, default:NoValue) –The maximum number of concurrent results to monitor at a time. This is useful when
itemsis a generator utilising Caller.to_thread. By default this will limit toCaller.MAX_IDLE_POOL_INSTANCES. -
(cancel_unfinished¶bool, default:True) –Cancel any
pendingwhen exiting.
Tip
- Pass a generator if you wish to limit the number result jobs when calling to_thread/to_task etc.
- Pass a container with all results when the limiter is not relevant.
Source code in src/async_kernel/caller.py
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 | |
wait
async
¶
wait(
items: Iterable[Awaitable[T]],
*,
timeout: float | None = None,
return_when: Literal[
"FIRST_COMPLETED", "FIRST_EXCEPTION", "ALL_COMPLETED"
] = "ALL_COMPLETED",
) -> tuple[set[Pending[T]], set[Pending[T]]]
Wait for the results given by items to complete.
Returns two sets of the results: (done, pending).
Parameters:
-
(items¶Iterable[Awaitable[T]]) –An iterable of results to wait for.
-
(timeout¶float | None, default:None) –The maximum time before returning.
-
(return_when¶Literal['FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED'], default:'ALL_COMPLETED') –The same options as available for asyncio.wait.
Example
done, pending = await asyncio.wait(items)
Info: - This does not raise a TimeoutError! - Pendings that aren't done when the timeout occurs are returned in the second set.
Source code in src/async_kernel/caller.py
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 | |
create_pending_group
¶
create_pending_group(*, shield: bool = False)
Create a new pending group.
Source code in src/async_kernel/caller.py
893 894 895 | |