flpit 0.4.2.dev1__tar.gz → 0.4.2.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/PKG-INFO +1 -1
  2. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/pyproject.toml +1 -1
  3. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/task.py +506 -73
  4. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/threading.py +76 -1
  5. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/.gitignore +0 -0
  6. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/LICENSE +0 -0
  7. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/README.md +0 -0
  8. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flp/__init__.py +0 -0
  9. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/__init__.py +0 -0
  10. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/channels.py +0 -0
  11. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/concurrent.py +0 -0
  12. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/__init__.py +0 -0
  13. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/_grouping.py +0 -0
  14. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/_index.py +0 -0
  15. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/_join.py +0 -0
  16. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/_lookup.py +0 -0
  17. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/_zip.py +0 -0
  18. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/async_linq.py +0 -0
  19. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/comparers.py +0 -0
  20. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/core/linq.py +0 -0
  21. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/csv.py +0 -0
  22. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/flp.py +0 -0
  23. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/json/__init__.py +0 -0
  24. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/json/_core.py +0 -0
  25. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/json/_msgspec.py +0 -0
  26. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/json/_native.py +0 -0
  27. {flpit-0.4.2.dev1 → flpit-0.4.2.dev3}/src/flpit/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flpit
3
- Version: 0.4.2.dev1
3
+ Version: 0.4.2.dev3
4
4
  Summary: Fluent LINQ for Python — flip your iterables
5
5
  Project-URL: Homepage, https://github.com/riemar/flpit
6
6
  Project-URL: Documentation, https://riemar.github.io/flpit/
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "flpit"
3
- version = "0.4.2.dev1"
3
+ version = "0.4.2.dev3"
4
4
  description = "Fluent LINQ for Python — flip your iterables"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -65,7 +65,7 @@ from collections.abc import AsyncGenerator, Generator
65
65
  from dataclasses import dataclass
66
66
  from itertools import count
67
67
  from types import AsyncGeneratorType, CoroutineType, FunctionType, MethodType
68
- from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, Iterable, Final, overload
68
+ from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast, Iterable, Final, overload
69
69
  import functools
70
70
  from functools import wraps
71
71
  from collections.abc import Awaitable, Callable, Coroutine
@@ -73,7 +73,8 @@ from contextlib import AsyncExitStack
73
73
  from contextvars import Context, ContextVar, copy_context
74
74
  from enum import IntFlag
75
75
  from datetime import timedelta
76
- from .threading import AsyncLocal, _run_with_context, _to_seconds
76
+ from .threading import _NO_STATE, AsyncLocal, _notify_context_exit, _run_with_context, _to_seconds
77
+ from . import threading as _context_flow
77
78
  from flpit.core.linq import ArgumentError, ArgumentNullError, ArgumentOutOfRangeError
78
79
 
79
80
  import flpit
@@ -231,6 +232,7 @@ _CREATION_OPTIONS_MASK: Final = int(
231
232
  | TaskCreationOptions.ATTACHED_TO_PARENT | TaskCreationOptions.DENY_CHILD_ATTACH
232
233
  | TaskCreationOptions.HIDE_SCHEDULER | TaskCreationOptions.RUN_CONTINUATIONS_ASYNCHRONOUSLY
233
234
  )
235
+ _LONG_RUNNING: Final = TaskCreationOptions.LONG_RUNNING.value
234
236
  _NOT_ON_ANYTHING: Final = int(
235
237
  TaskContinuationOptions.NOT_ON_RAN_TO_COMPLETION | TaskContinuationOptions.NOT_ON_FAULTED
236
238
  | TaskContinuationOptions.NOT_ON_CANCELED
@@ -399,6 +401,7 @@ class _TimerQueue:
399
401
  _thread_state.internal = True
400
402
  condition = self._condition
401
403
  due: list[Callable[[], Any]] = []
404
+ park = cast(float, _park_interval(self._MAX_WAIT))
402
405
  while True:
403
406
  with condition:
404
407
  while True:
@@ -419,9 +422,9 @@ class _TimerQueue:
419
422
  if due:
420
423
  break
421
424
  if heap:
422
- condition.wait(min(heap[0][0] - now, self._MAX_WAIT))
425
+ condition.wait(min(heap[0][0] - now, park))
423
426
  else:
424
- condition.wait()
427
+ condition.wait(_park_interval(None))
425
428
  for callback in due:
426
429
  try:
427
430
  callback()
@@ -781,6 +784,13 @@ def _close_if_coroutine(value: Any) -> None:
781
784
  value.close()
782
785
 
783
786
 
787
+ # Result types of synchronous work that are never awaitable; checking for them
788
+ # first spares the comparatively slow inspect.isawaitable() for most results.
789
+ _NEVER_AWAITABLE: Final = frozenset(
790
+ {type(None), bool, int, float, complex, str, bytes, bytearray, tuple, list, dict, set, frozenset}
791
+ )
792
+
793
+
784
794
  async def _await_any(awaitable: Any) -> Any:
785
795
  return await awaitable
786
796
 
@@ -813,6 +823,28 @@ class Task(Generic[T], metaclass=_TaskMeta):
813
823
  """The options the task was created with (.NET ``Task.CreationOptions``)."""
814
824
  return self._creation_options
815
825
 
826
+ # Per-task state that most tasks never change. The defaults live on the class
827
+ # and a task only gets its own attribute when it assigns one: a Task is created
828
+ # for every unit of work, and each attribute stored in __init__ costs time.
829
+ _result: Any = None
830
+ _exception: BaseException | None = None
831
+ _continuations: list[Callable[[Task[Any]], Any]] | None = None
832
+ _done_event: threading.Event | None = None
833
+ _work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
834
+ _coroutine: Coroutine[Any, Any, Any] | None = None
835
+ _waiting_on: _Operation | None = None
836
+ _running: bool = False
837
+ _sync_running: bool = False
838
+ _next_value: Any = None
839
+ _next_exception: BaseException | None = None
840
+ _cancel_requested: bool = False
841
+ _token_registration: CancellationTokenRegistration | None = None
842
+ _timer: _TimerHandle | None = None
843
+ _pass_token: bool = False
844
+ _is_promise_task: bool = False
845
+ _name: str | None = None
846
+ async_state: Any = None
847
+
816
848
  def __init__(
817
849
  self,
818
850
  runtime: "_Runtime",
@@ -824,29 +856,16 @@ class Task(Generic[T], metaclass=_TaskMeta):
824
856
  # Guards the state transition, the continuation list and parking.
825
857
  self._lock = threading.Lock()
826
858
  self._state: str = _PENDING
827
- self._result: Any = None
828
- self._exception: BaseException | None = None
829
- self._continuations: list[Callable[[Task[Any]], Any]] | None = None
830
- self._done_event: threading.Event | None = None
831
859
  # Promise-style tasks never run code and need no execution context.
860
+ # The context holds this task as the current task, so the two form a
861
+ # reference cycle. Every path on which the task's code has finished
862
+ # drops the context ("see _release_context"): otherwise a finished
863
+ # task, its result and every AsyncLocal value set inside it would only
864
+ # be freed by the cyclic garbage collector.
832
865
  self._execution_context: Context | None = (
833
866
  copy_context() if capture_context else None
834
867
  )
835
- self._work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
836
- self._coroutine: Coroutine[Any, Any, Any] | None = None
837
- self._waiting_on: _Operation | None = None
838
- self._running = False
839
- self._sync_running = False
840
- self._next_value: Any = None
841
- self._next_exception: BaseException | None = None
842
- self._cancel_requested = False
843
868
  self._token = token if token is not None else _NONE_TOKEN
844
- self._token_registration: CancellationTokenRegistration | None = None
845
- self._timer: _TimerHandle | None = None
846
- self._pass_token = False
847
- self._is_promise_task = False
848
- self._name: str | None = None
849
- self.async_state: Any = None
850
869
 
851
870
  @property
852
871
  def name(self) -> str:
@@ -980,7 +999,126 @@ class Task(Generic[T], metaclass=_TaskMeta):
980
999
  ``creation_options`` (.NET ``TaskFactory.StartNew``): ``LONG_RUNNING`` runs
981
1000
  the work on a dedicated thread instead of a pool worker, for work that
982
1001
  blocks for a long time; see ``TaskCreationOptions`` for the others.
1002
+
1003
+ The work always starts on the pool, never on the calling thread; use
1004
+ ``Task.run_inline`` to start it on the calling thread instead.
983
1005
  """
1006
+ task = cls._create(work, args, kwargs, token, pass_token, creation_options)
1007
+ if creation_options and creation_options & _LONG_RUNNING:
1008
+ task._runtime._submit_long_running(task, work, args, kwargs)
1009
+ else:
1010
+ task._runtime._submit(task, work, args, kwargs)
1011
+ return task
1012
+
1013
+ @overload
1014
+ @classmethod
1015
+ def run_inline[R](
1016
+ cls,
1017
+ work: Callable[..., Coroutine[Any, Any, R]],
1018
+ /,
1019
+ *args: Any,
1020
+ token: CancellationToken | None = None,
1021
+ pass_token: bool = False,
1022
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1023
+ **kwargs: Any,
1024
+ ) -> Task[R]: ...
1025
+
1026
+ @overload
1027
+ @classmethod
1028
+ def run_inline[R](
1029
+ cls,
1030
+ work: Coroutine[Any, Any, R],
1031
+ /,
1032
+ *,
1033
+ token: CancellationToken | None = None,
1034
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1035
+ ) -> Task[R]: ...
1036
+
1037
+ @overload
1038
+ @classmethod
1039
+ def run_inline[R](
1040
+ cls,
1041
+ work: Callable[..., R],
1042
+ /,
1043
+ *args: Any,
1044
+ token: CancellationToken | None = None,
1045
+ pass_token: bool = False,
1046
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1047
+ **kwargs: Any,
1048
+ ) -> Task[R]: ...
1049
+
1050
+ @classmethod
1051
+ def run_inline(
1052
+ cls,
1053
+ work: Any,
1054
+ /,
1055
+ *args: Any,
1056
+ token: CancellationToken | None = None,
1057
+ pass_token: bool = False,
1058
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1059
+ **kwargs: Any,
1060
+ ) -> Task[Any]:
1061
+ """Start ``work`` on the calling thread and return a Task for the rest of it.
1062
+
1063
+ This is how calling an ``async`` method behaves in .NET: the coroutine runs
1064
+ synchronously on the calling thread until its first ``await`` of something that
1065
+ has not completed yet. Only then does the caller get control back, holding a
1066
+ pending Task; after that point the coroutine resumes on the pool, as with
1067
+ ``Task.run``. A coroutine that never really suspends has completed when this
1068
+ returns, without a queue hop or a wake-up. A synchronous callable runs to its
1069
+ end on the calling thread.
1070
+
1071
+ Accepts the same arguments as ``Task.run``: a coroutine object or other
1072
+ awaitable, or a callable with its arguments. In detail:
1073
+
1074
+ * **Exceptions** raised before the first suspension complete the returned Task
1075
+ (faulted, or canceled for ``OperationCanceledError``); they are not raised into
1076
+ the caller.
1077
+ * **Awaiting something already complete** continues at once, on the same thread.
1078
+ ``await Task.yield_now()`` is a real suspension: the rest runs on the pool.
1079
+ * **Context:** the work runs in a copy of the caller's ``contextvars`` context, so
1080
+ ``AsyncLocal`` changes made inside never reach the caller.
1081
+ * **Cancellation:** an already cancelled ``token`` gives a canceled Task without
1082
+ running anything, as with ``Task.run``.
1083
+ * **Nesting:** each nested inline start adds to the calling thread's stack. Past a
1084
+ fixed depth (shared with ``Task.result()``, which also runs tasks inline) the
1085
+ work is queued to the pool instead, as ``Task.run`` does. The runtime's own
1086
+ timer and IO threads never run user code: called there, it queues as well.
1087
+
1088
+ ``creation_options`` behave as in ``Task.run``, except ``LONG_RUNNING``, which asks
1089
+ for a dedicated thread and is rejected.
1090
+ """
1091
+ if creation_options and isinstance(creation_options, int) and creation_options & _LONG_RUNNING:
1092
+ _close_if_coroutine(work)
1093
+ raise ArgumentOutOfRangeError(
1094
+ "creationOptions", "LONG_RUNNING cannot be combined with Task.run_inline()."
1095
+ )
1096
+ task = cls._create(work, args, kwargs, token, pass_token, creation_options)
1097
+ runtime = task._runtime
1098
+ state = _thread_state
1099
+ if state.internal or state.inline >= _MAX_INLINE_DEPTH:
1100
+ runtime._submit(task, work, args, kwargs)
1101
+ return task
1102
+ kind = type(work)
1103
+ if kind is CoroutineType or (
1104
+ (kind is FunctionType or kind is MethodType) and _is_coroutine_function(work)
1105
+ ):
1106
+ task._run_coroutine_inline(state, work, args, kwargs)
1107
+ else:
1108
+ runtime._submit_inline(task, work, args, kwargs, state)
1109
+ return task
1110
+
1111
+ @classmethod
1112
+ def _create(
1113
+ cls,
1114
+ work: Any,
1115
+ args: tuple[Any, ...],
1116
+ kwargs: dict[str, Any],
1117
+ token: CancellationToken | None,
1118
+ pass_token: bool,
1119
+ creation_options: TaskCreationOptions,
1120
+ ) -> Task[Any]:
1121
+ """Validate ``Task.run`` arguments and create the (not yet submitted) task."""
984
1122
  kind = type(work)
985
1123
  is_coroutine = kind is CoroutineType
986
1124
  if kind is FunctionType or kind is MethodType:
@@ -1006,16 +1144,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
1006
1144
  if is_coroutine:
1007
1145
  cast(Any, work).close()
1008
1146
  raise ArgumentOutOfRangeError("creationOptions", "The value needs to be a valid TaskCreationOptions.")
1009
- runtime = _get_runtime()
1010
- task = cls(runtime, token=token)
1011
- task._pass_token = pass_token
1012
- task._creation_options = TaskCreationOptions(creation_options)
1013
- if creation_options & TaskCreationOptions.RUN_CONTINUATIONS_ASYNCHRONOUSLY:
1014
- task._async_continuations = True
1015
- if creation_options & TaskCreationOptions.LONG_RUNNING:
1016
- runtime._submit_long_running(task, work, args, kwargs)
1017
- else:
1018
- runtime._submit(task, work, args, kwargs)
1147
+ task = cls(_get_runtime(), token=token)
1148
+ if pass_token:
1149
+ task._pass_token = True
1150
+ if creation_options:
1151
+ task._creation_options = TaskCreationOptions(creation_options)
1152
+ if creation_options & TaskCreationOptions.RUN_CONTINUATIONS_ASYNCHRONOUSLY:
1153
+ task._async_continuations = True
1019
1154
  return task
1020
1155
 
1021
1156
  @overload
@@ -1433,7 +1568,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1433
1568
  and pool is self._runtime._pool
1434
1569
  and state.inline < _MAX_INLINE_DEPTH
1435
1570
  ):
1436
- self._run_inline(state, pool)
1571
+ self._run_inline(state)
1437
1572
  with self._lock:
1438
1573
  if self._state is not _PENDING:
1439
1574
  return
@@ -1449,30 +1584,117 @@ class Task(Generic[T], metaclass=_TaskMeta):
1449
1584
  finally:
1450
1585
  pool._worker_unblocked()
1451
1586
 
1452
- def _run_inline(self, state: _ThreadState, pool: "_WorkerPool") -> None:
1453
- """Start this task on the calling worker instead of waiting for it.
1587
+ def _run_inline(self, state: _ThreadState) -> None:
1588
+ """Start this task on the calling thread instead of on a pool worker.
1454
1589
 
1455
- ``_start()`` takes the work under the task's lock, so either this
1456
- thread or the worker that pops the queued item runs it, never both;
1457
- the loser finds nothing to do.
1590
+ Used by ``Task.result()`` for a task that has not started, and by
1591
+ ``Task.run_inline``. ``_start()`` takes the work under the task's
1592
+ lock, so either this thread or a worker that pops a queued item runs
1593
+ it, never both; the loser finds nothing to do.
1458
1594
  """
1459
- tail = state.tail
1460
- state.inline += 1
1595
+ tail, hooks = _enter_inline(state)
1461
1596
  try:
1462
1597
  self._start()
1463
1598
  finally:
1464
- state.inline -= 1
1465
- # The caller is still inside its own work item. Anything the
1466
- # inlined task left for "this worker's next item" must not wait
1467
- # until the caller returns -- the caller may be about to block on
1468
- # exactly that.
1469
- state.tail = tail
1470
- item = state.slot
1471
- if item is not None:
1472
- state.slot = None
1473
- # False only if the pool closed, and then shutdown has
1474
- # already cancelled the task behind the item.
1475
- pool.queue(item)
1599
+ _exit_inline(state, tail, hooks)
1600
+
1601
+ def _run_coroutine_inline(
1602
+ self, state: _ThreadState, target: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
1603
+ ) -> None:
1604
+ """``Task.run_inline`` of a coroutine: run its first step on the calling thread.
1605
+
1606
+ The same as ``_start()`` followed by ``_drive()``, minus what the first step
1607
+ of a task that nobody else has seen yet does not need. The task counts as
1608
+ running from the moment it is registered, so a concurrent shutdown treats it
1609
+ like any running coroutine: cancellation is delivered at its next step
1610
+ boundary. On the first suspension it is handed to the usual machinery.
1611
+ """
1612
+ runtime = self._runtime
1613
+ self._running = True
1614
+ try:
1615
+ runtime._track(self)
1616
+ except BaseException:
1617
+ _close_if_coroutine(target)
1618
+ raise
1619
+ token = self._token
1620
+ if token.is_cancellation_requested:
1621
+ _close_if_coroutine(target)
1622
+ self._finish(
1623
+ _CANCELLED,
1624
+ exception=OperationCanceledError(f"{self.name} cancelled before start", token=token),
1625
+ )
1626
+ return
1627
+
1628
+ context = cast(Context, self._execution_context)
1629
+ # The bookkeeping of _enter_inline()/_exit_inline(), spelled out: thread-local
1630
+ # attributes are slow, and a coroutine that finishes in its first step needs
1631
+ # few of them. ``tail`` stays False while the step runs (as in _drive), so
1632
+ # anything the step makes runnable goes to the shared queue directly.
1633
+ tail = state.tail
1634
+ if tail:
1635
+ state.tail = False
1636
+ pool = state.pool
1637
+ hooks = None
1638
+ if pool is None:
1639
+ hooks = sys.get_asyncgen_hooks()
1640
+ if hooks.firstiter is _asyncgen_firstiter:
1641
+ hooks = None
1642
+ else:
1643
+ _install_asyncgen_hooks()
1644
+ depth = state.inline
1645
+ state.inline = depth + 1
1646
+ drove = False
1647
+ try:
1648
+ context.run(_current_task._value.set, self)
1649
+ try:
1650
+ if type(target) is CoroutineType:
1651
+ coroutine = target
1652
+ else:
1653
+ if self._pass_token:
1654
+ kwargs = {**kwargs, "token": token}
1655
+ # Only creates the coroutine object; no user code runs yet.
1656
+ coroutine = context.run(target, *args, **kwargs)
1657
+ if _context_flow._notifications_enabled:
1658
+ yielded = _run_with_context(context, coroutine.send, None)
1659
+ else:
1660
+ try:
1661
+ yielded = context.run(coroutine.send, None)
1662
+ finally:
1663
+ if _context_flow._notifications_enabled:
1664
+ _notify_context_exit(context)
1665
+ except StopIteration as stop:
1666
+ self._finish(_SUCCEEDED, result=stop.value)
1667
+ self._execution_context = None # break the cycle with the context
1668
+ return
1669
+ except OperationCanceledError as cancellation:
1670
+ self._finish(_CANCELLED, exception=cancellation)
1671
+ self._execution_context = None # break the cycle with the context
1672
+ return
1673
+ except BaseException as failure:
1674
+ self._finish(_FAILED, exception=failure)
1675
+ self._execution_context = None # break the cycle with the context
1676
+ return
1677
+
1678
+ # The first real suspension (or an await that _suspend resolves at once).
1679
+ drove = True
1680
+ state.tail = True
1681
+ self._coroutine = coroutine
1682
+ try:
1683
+ resume = runtime._suspend(self, yielded)
1684
+ except BaseException as failure:
1685
+ with self._lock:
1686
+ resume = self._running or self._waiting_on is yielded
1687
+ if resume:
1688
+ self._waiting_on = None
1689
+ self._next_exception = failure
1690
+ if resume:
1691
+ self._drive()
1692
+ finally:
1693
+ state.inline = depth
1694
+ if tail or drove:
1695
+ _exit_inline_slot(state, tail)
1696
+ if hooks is not None:
1697
+ sys.set_asyncgen_hooks(*hooks)
1476
1698
 
1477
1699
  def _add_continuation(self, continuation: Callable[[Task[Any]], Any]) -> bool:
1478
1700
  """Call ``continuation(self)`` on completion; False if already complete.
@@ -1577,17 +1799,27 @@ class Task(Generic[T], metaclass=_TaskMeta):
1577
1799
  with self._lock:
1578
1800
  if self._state is not _PENDING:
1579
1801
  return False
1580
- self._result = result
1581
- self._exception = exception
1802
+ # Fields still at their class default (None) are only read: storing
1803
+ # None would give every task an instance attribute of its own.
1804
+ if result is not None:
1805
+ self._result = result
1806
+ if exception is not None:
1807
+ tb = exception.__traceback__
1808
+ if tb is not None and tb.tb_frame.f_code in _RUNTIME_CODES:
1809
+ exception.__traceback__ = _without_runtime_frames(tb)
1810
+ self._exception = exception
1582
1811
  # Published last: lock-free readers check the state first.
1583
1812
  self._state = state
1584
1813
  continuations = self._continuations
1585
- self._continuations = None
1814
+ if continuations is not None:
1815
+ self._continuations = None
1586
1816
  event = self._done_event
1587
1817
  registration = self._token_registration
1588
- self._token_registration = None
1818
+ if registration is not None:
1819
+ self._token_registration = None
1589
1820
  timer = self._timer
1590
- self._timer = None
1821
+ if timer is not None:
1822
+ self._timer = None
1591
1823
  if registration is not None:
1592
1824
  registration.dispose()
1593
1825
  if timer is not None:
@@ -1673,9 +1905,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1673
1905
  # The context belongs to this task alone, so the current task is
1674
1906
  # set once instead of being set and restored around every step.
1675
1907
  context.run(_current_task._value.set, self)
1676
- if type(target) is CoroutineType:
1908
+ kind = type(target)
1909
+ if kind is CoroutineType:
1677
1910
  value = target
1678
- elif inspect.isawaitable(target):
1911
+ elif kind is not FunctionType and kind is not MethodType and inspect.isawaitable(target):
1679
1912
  value = _await_any(target)
1680
1913
  else:
1681
1914
  if self._pass_token:
@@ -1690,21 +1923,25 @@ class Task(Generic[T], metaclass=_TaskMeta):
1690
1923
  finally:
1691
1924
  self._sync_running = False
1692
1925
  state.tail = True
1693
- if type(value) is CoroutineType:
1926
+ kind = type(value)
1927
+ if kind is CoroutineType:
1694
1928
  coroutine = value
1695
- elif inspect.isawaitable(value):
1929
+ elif kind not in _NEVER_AWAITABLE and inspect.isawaitable(value):
1696
1930
  # Support sync wrappers that return an awaitable.
1697
1931
  coroutine = _await_any(value)
1698
1932
  else:
1699
1933
  self._finish(_SUCCEEDED, result=value)
1934
+ self._execution_context = None # break the cycle with the context
1700
1935
  return
1701
1936
  except OperationCanceledError as error:
1702
1937
  state.tail = True
1703
1938
  self._finish(_CANCELLED, exception=error)
1939
+ self._execution_context = None # break the cycle with the context
1704
1940
  return
1705
1941
  except BaseException as error:
1706
1942
  state.tail = True
1707
1943
  self._finish(_FAILED, exception=error)
1944
+ self._execution_context = None # break the cycle with the context
1708
1945
  return
1709
1946
 
1710
1947
  self._coroutine = coroutine
@@ -1730,8 +1967,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1730
1967
  self._running = True
1731
1968
  value = self._next_value
1732
1969
  error = self._next_exception
1733
- self._next_value = None
1734
- self._next_exception = None
1970
+ if value is not None:
1971
+ self._next_value = None
1972
+ if error is not None:
1973
+ self._next_exception = None
1735
1974
  if self._cancel_requested:
1736
1975
  self._cancel_requested = False
1737
1976
  if not isinstance(error, OperationCanceledError):
@@ -1748,24 +1987,41 @@ class Task(Generic[T], metaclass=_TaskMeta):
1748
1987
 
1749
1988
  state.tail = False
1750
1989
  try:
1751
- if error is None:
1752
- yielded = _run_with_context(context, coroutine.send, value)
1990
+ if _context_flow._notifications_enabled:
1991
+ if error is None:
1992
+ yielded = _run_with_context(context, coroutine.send, value)
1993
+ else:
1994
+ yielded = _run_with_context(context, coroutine.throw, error)
1753
1995
  else:
1754
- yielded = _run_with_context(context, coroutine.throw, error)
1996
+ # _run_with_context without AsyncLocal change handlers, inlined:
1997
+ # every step of every coroutine runs through here, and the
1998
+ # StopIteration that ends one is costly to pass through a frame.
1999
+ try:
2000
+ if error is None:
2001
+ yielded = context.run(coroutine.send, value)
2002
+ else:
2003
+ yielded = context.run(coroutine.throw, error)
2004
+ finally:
2005
+ if _context_flow._notifications_enabled:
2006
+ # A handler was installed while the step ran.
2007
+ _notify_context_exit(context)
1755
2008
  except StopIteration as stop:
1756
2009
  state.tail = True
1757
2010
  self._coroutine = None
1758
2011
  self._finish(_SUCCEEDED, result=stop.value)
2012
+ self._execution_context = None # break the cycle with the context
1759
2013
  return
1760
2014
  except OperationCanceledError as cancellation:
1761
2015
  state.tail = True
1762
2016
  self._coroutine = None
1763
2017
  self._finish(_CANCELLED, exception=cancellation)
2018
+ self._execution_context = None # break the cycle with the context
1764
2019
  return
1765
2020
  except BaseException as failure:
1766
2021
  state.tail = True
1767
2022
  self._coroutine = None
1768
2023
  self._finish(_FAILED, exception=failure)
2024
+ self._execution_context = None # break the cycle with the context
1769
2025
  return
1770
2026
 
1771
2027
  state.tail = True
@@ -1855,6 +2111,23 @@ class Task(Generic[T], metaclass=_TaskMeta):
1855
2111
 
1856
2112
  _current_task: AsyncLocal[Task[Any] | None] = AsyncLocal()
1857
2113
 
2114
+ # The runtime's own frames, which head the traceback of an exception that escapes a
2115
+ # task's code. They tell the user nothing, and their locals include the task itself:
2116
+ # kept in the stored exception, they would tie the task, its exception and everything
2117
+ # the traceback references into a cycle that only the cyclic GC can free.
2118
+ _RUNTIME_CODES: Final = frozenset({
2119
+ Task._start.__code__,
2120
+ Task._drive.__code__,
2121
+ Task._run_coroutine_inline.__code__,
2122
+ _run_with_context.__code__,
2123
+ })
2124
+
2125
+
2126
+ def _without_runtime_frames(tb: Any) -> Any:
2127
+ while tb is not None and tb.tb_frame.f_code in _RUNTIME_CODES:
2128
+ tb = tb.tb_next
2129
+ return tb
2130
+
1858
2131
 
1859
2132
  # ---------------------------------------------------------------------------
1860
2133
  # Async generators (PEP 525 hooks)
@@ -2722,8 +2995,9 @@ class _IOReactor:
2722
2995
  commands = self._commands
2723
2996
  failure: BaseException | None = None
2724
2997
  try:
2998
+ park = _park_interval(None)
2725
2999
  while not self._closing:
2726
- for key, mask in selector.select(None):
3000
+ for key, mask in selector.select(park):
2727
3001
  if key.data is _WAKE:
2728
3002
  try:
2729
3003
  while reader.recv(4096):
@@ -2779,6 +3053,27 @@ class _IOReactor:
2779
3053
  return not thread.is_alive()
2780
3054
 
2781
3055
 
3056
+ def _park_interval(longest: float | None) -> float | None:
3057
+ """How long a runtime thread may block in one go while it has nothing to do.
3058
+
3059
+ On free-threaded builds an object is freed by the thread that created it: when
3060
+ another thread drops the last reference, the object is queued to its creator,
3061
+ which frees it the next time it runs Python code. A thread blocked for a long
3062
+ time would keep such objects (and everything they reference) alive. So there,
3063
+ idle threads wake up regularly. With the GIL, objects are freed at once and
3064
+ ``longest`` is kept.
3065
+ """
3066
+ gil_enabled = getattr(sys, "_is_gil_enabled", None)
3067
+ if gil_enabled is None or gil_enabled():
3068
+ return longest
3069
+ return _FREE_THREADED_PARK if longest is None else min(longest, _FREE_THREADED_PARK)
3070
+
3071
+
3072
+ # Free-threaded builds: the longest an idle runtime thread blocks without running
3073
+ # Python code (see _park_interval). Each wake-up costs a few microseconds.
3074
+ _FREE_THREADED_PARK: Final = 0.5
3075
+
3076
+
2782
3077
  def _spin_count() -> int:
2783
3078
  """How long an idle worker polls for work before it parks.
2784
3079
 
@@ -2929,6 +3224,7 @@ class _WorkerPool:
2929
3224
  parker.acquire()
2930
3225
  searching = True # whoever started this thread counted it as such
2931
3226
  counted = True
3227
+ park = cast(float, _park_interval(self._IDLE_TIMEOUT))
2932
3228
  try:
2933
3229
  while True:
2934
3230
  item = state.slot
@@ -2984,7 +3280,13 @@ class _WorkerPool:
2984
3280
  searching = True
2985
3281
  continue
2986
3282
 
2987
- while not parker.acquire(timeout=self._IDLE_TIMEOUT):
3283
+ idle_since = time.monotonic()
3284
+ while not parker.acquire(timeout=park):
3285
+ # Waking up ran Python code: objects this thread
3286
+ # created and others released are freed now.
3287
+ if time.monotonic() - idle_since < self._IDLE_TIMEOUT:
3288
+ continue
3289
+ idle_since = time.monotonic()
2988
3290
  with lock:
2989
3291
  if parker not in self._parked:
2990
3292
  # A waker picked this worker just now.
@@ -3196,6 +3498,19 @@ class _Runtime:
3196
3498
  # If the pool closes in between, shutdown's final sweep cancels the task.
3197
3499
  self._pool.queue(task._start)
3198
3500
 
3501
+ def _submit_inline(
3502
+ self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any], state: _ThreadState
3503
+ ) -> None:
3504
+ """Task.run_inline: start the task on the calling thread right away."""
3505
+ task._work = (work, args, kwargs)
3506
+ try:
3507
+ self._track(task)
3508
+ except BaseException:
3509
+ task._work = None
3510
+ _close_if_coroutine(work)
3511
+ raise
3512
+ task._run_inline(state)
3513
+
3199
3514
  def _submit_long_running(
3200
3515
  self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
3201
3516
  ) -> None:
@@ -3459,6 +3774,81 @@ class _Runtime:
3459
3774
  return report
3460
3775
 
3461
3776
 
3777
+ def _queue_work_item(callback: Any, state: Any, *, flow_context: bool) -> bool:
3778
+ """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task."""
3779
+ if callback is None:
3780
+ raise ArgumentNullError("callBack")
3781
+ if not callable(callback):
3782
+ raise TypeError("callback must be callable")
3783
+ runtime = _get_runtime()
3784
+ if flow_context:
3785
+ context = copy_context()
3786
+ if context.get(_current_task._value) is not None:
3787
+ # A work item is not part of the task that queued it.
3788
+ context.run(_current_task._value.set, None)
3789
+ else:
3790
+ context = Context()
3791
+ runtime._post(functools.partial(_run_work_item, runtime, context, callback, state))
3792
+ return True
3793
+
3794
+
3795
+ def _run_work_item(runtime: _Runtime, context: Context, callback: Callable[..., Any], state: Any) -> None:
3796
+ try:
3797
+ if state is _NO_STATE:
3798
+ _run_with_context(context, callback)
3799
+ else:
3800
+ _run_with_context(context, callback, state)
3801
+ except BaseException as error:
3802
+ runtime._report_exception(
3803
+ {"message": "Unhandled exception in a thread-pool work item", "callback": callback}, error
3804
+ )
3805
+
3806
+
3807
+ def _enter_inline(state: _ThreadState) -> tuple[bool, Any]:
3808
+ """Bookkeeping before a task runs inline on the calling thread.
3809
+
3810
+ Returns what ``_exit_inline`` restores. Pool workers and LONG_RUNNING threads
3811
+ have flpit's async generator hooks; any other thread gets them for the time
3812
+ being, so that async generators the task starts are tracked as on the pool.
3813
+ """
3814
+ hooks = None
3815
+ if state.pool is None:
3816
+ hooks = sys.get_asyncgen_hooks()
3817
+ if hooks.firstiter is _asyncgen_firstiter:
3818
+ hooks = None
3819
+ else:
3820
+ _install_asyncgen_hooks()
3821
+ state.inline += 1
3822
+ return state.tail, hooks
3823
+
3824
+
3825
+ def _exit_inline(state: _ThreadState, tail: bool, hooks: Any) -> None:
3826
+ state.inline -= 1
3827
+ _exit_inline_slot(state, tail)
3828
+ if hooks is not None:
3829
+ sys.set_asyncgen_hooks(*hooks)
3830
+
3831
+
3832
+ def _exit_inline_slot(state: _ThreadState, tail: bool) -> None:
3833
+ # The caller is still inside its own work item. Anything the inlined task
3834
+ # left for "this worker's next item" must not wait until the caller
3835
+ # returns -- the caller may be about to block on exactly that. (Only pool
3836
+ # workers ever fill the slot.)
3837
+ state.tail = tail
3838
+ item = state.slot
3839
+ if item is not None:
3840
+ state.slot = None
3841
+ # False only if the pool closed, and then shutdown has already
3842
+ # cancelled the task behind the item.
3843
+ cast("_WorkerPool", state.pool).queue(item)
3844
+
3845
+
3846
+ def _is_coroutine_function(function: Any) -> bool:
3847
+ """True for an ``async def`` function or bound method, by its code flags alone."""
3848
+ code = getattr(function.__func__ if type(function) is MethodType else function, "__code__", None)
3849
+ return code is not None and bool(code.co_flags & inspect.CO_COROUTINE)
3850
+
3851
+
3462
3852
  def _is_async_callable(value: Any) -> bool:
3463
3853
  function = value.__func__ if type(value) is MethodType else value
3464
3854
  if type(function) is FunctionType:
@@ -3529,20 +3919,63 @@ if hasattr(os, "register_at_fork"):
3529
3919
  os.register_at_fork(after_in_child=_reset_after_fork)
3530
3920
 
3531
3921
 
3922
+ class _TaskDecorator(Protocol):
3923
+ """What ``task(inline=...)`` returns: the decorator itself."""
3924
+
3925
+ @overload
3926
+ def __call__[**P, T](self, function: Callable[P, Awaitable[T]], /) -> Callable[P, Task[T]]: ...
3927
+
3928
+ @overload
3929
+ def __call__[**P, T](self, function: Callable[P, T], /) -> Callable[P, Task[T]]: ...
3930
+
3931
+
3532
3932
  @overload
3533
3933
  def task[**P, T](
3534
- function: Callable[P, Awaitable[T]]
3934
+ function: Callable[P, Awaitable[T]], /
3535
3935
  ) -> Callable[P, Task[T]]: ...
3536
3936
 
3537
3937
  @overload
3538
3938
  def task[**P, T](
3539
- function: Callable[P, T]
3939
+ function: Callable[P, T], /
3540
3940
  ) -> Callable[P, Task[T]]: ...
3541
3941
 
3542
- def task(function: Callable[..., Any]) -> Callable[..., Task[Any]]:
3543
- """
3544
- | Wraps sync functions and non-asyncio dependent coroutines to eagerly executed await-able tasks
3942
+ @overload
3943
+ def task(*, inline: bool = False) -> _TaskDecorator: ...
3944
+
3945
+ def task(function: Callable[..., Any] | None = None, /, *, inline: bool = False) -> Any:
3946
+ """Make every call of ``function`` start a Task and return it.
3947
+
3948
+ ``@task`` starts each call with ``Task.run``: queued to the pool, for plain and
3949
+ ``async def`` functions alike. That is .NET's ``Task.Run`` on every call.
3950
+
3951
+ ``@task(inline=True)`` is for ``async def`` functions only and starts each call with
3952
+ ``Task.run_inline``: the coroutine runs on the calling thread until its first
3953
+ ``await`` of something not yet complete, which is how calling an ``async`` method
3954
+ behaves in .NET. A plain function is rejected, because running it inline would just
3955
+ be calling it.
3545
3956
  """
3957
+ if function is None:
3958
+ def decorator(target: Callable[..., Any], /) -> Callable[..., Task[Any]]:
3959
+ return _task_wrapper(target, inline)
3960
+
3961
+ return decorator
3962
+ return _task_wrapper(function, inline)
3963
+
3964
+
3965
+ def _task_wrapper(function: Callable[..., Any], inline: bool) -> Callable[..., Task[Any]]:
3966
+ if inline:
3967
+ if not _is_async_callable(function):
3968
+ raise TypeError(
3969
+ "@task(inline=True) needs an async def function: a plain function started "
3970
+ "inline would simply run to its end at the call. Use @task for it."
3971
+ )
3972
+
3973
+ @wraps(function)
3974
+ def inline_wrapper(*args: Any, **kwargs: Any) -> Task[Any]:
3975
+ return Task.run_inline(function, *args, **kwargs)
3976
+
3977
+ return inline_wrapper
3978
+
3546
3979
  @wraps(function)
3547
3980
  def wrapper(*args: Any, **kwargs: Any) -> Task[Any]:
3548
3981
  return Task.run(function, *args, **kwargs)
@@ -9,7 +9,7 @@ from collections.abc import Callable
9
9
  from contextvars import Context, ContextVar
10
10
  from dataclasses import dataclass
11
11
  from datetime import timedelta
12
- from typing import TYPE_CHECKING, Any, Final, cast
12
+ from typing import TYPE_CHECKING, Any, Final, cast, overload
13
13
 
14
14
  from flpit.core.linq import ArgumentNullError, ArgumentOutOfRangeError, InvalidOperationError
15
15
 
@@ -383,6 +383,81 @@ class ThreadLocal[T]:
383
383
  # Wait handles, timeouts and SemaphoreSlim (System.Threading)
384
384
  # =============================================================================
385
385
 
386
+ # Marks an omitted ``state`` argument: ``None`` is a valid state.
387
+ _NO_STATE: Final = object()
388
+
389
+
390
+ class ThreadPool:
391
+ """Queue plain work items on the Task runtime's worker pool (.NET ``ThreadPool``).
392
+
393
+ A work item is a function call and nothing more: no Task is created, there is no
394
+ result to wait for and nothing to cancel. That makes it the cheapest way to get a
395
+ call onto a pool worker, for example from a thread that is not one (an IO thread
396
+ of a server) and must hand off at once. Use ``Task.run`` when you need a result,
397
+ an exception, cancellation or ``await``.
398
+
399
+ The pool is the one ``Task.run`` uses, so ``Task.configure`` sizes it and
400
+ ``Task.shutdown`` stops it.
401
+
402
+ Example:
403
+ ```python
404
+ ThreadPool.queue(handle_request, request)
405
+ ```
406
+ """
407
+
408
+ __slots__ = ()
409
+
410
+ @overload
411
+ @staticmethod
412
+ def queue(callback: Callable[[], object], /) -> bool: ...
413
+
414
+ @overload
415
+ @staticmethod
416
+ def queue[S](callback: Callable[[S], object], state: S, prefer_local: bool = False) -> bool: ...
417
+
418
+ @staticmethod
419
+ def queue(
420
+ callback: Callable[..., object], state: Any = _NO_STATE, prefer_local: bool = False
421
+ ) -> bool:
422
+ """Queue ``callback(state)``, or ``callback()`` without ``state``, on a pool worker.
423
+
424
+ As .NET ``ThreadPool.UnsafeQueueUserWorkItem``, nothing of the caller's execution
425
+ context flows: the call runs in a fresh, empty ``contextvars.Context``. It sees no
426
+ ``AsyncLocal`` value of the caller, and what it sets stays inside the work item
427
+ (a pool thread's context is never changed, as .NET resets it after each item).
428
+
429
+ An exception that escapes ``callback`` goes to the handler installed with
430
+ ``Task.set_exception_handler``, or is logged when there is none. (.NET
431
+ terminates the process instead.)
432
+
433
+ ``prefer_local`` is accepted for porting and has no effect: the pool has one
434
+ shared queue. Returns ``True``. Raises ``RuntimeShutdownError`` while the runtime
435
+ is shutting down.
436
+ """
437
+ return _task._queue_work_item(callback, state, flow_context=False)
438
+
439
+ @overload
440
+ @staticmethod
441
+ def queue_user_work_item(callback: Callable[[], object], /) -> bool: ...
442
+
443
+ @overload
444
+ @staticmethod
445
+ def queue_user_work_item[S](callback: Callable[[S], object], state: S, prefer_local: bool = False) -> bool: ...
446
+
447
+ @staticmethod
448
+ def queue_user_work_item(
449
+ callback: Callable[..., object], state: Any = _NO_STATE, prefer_local: bool = False
450
+ ) -> bool:
451
+ """Queue ``callback(state)``, or ``callback()``, with the caller's execution context.
452
+
453
+ As .NET ``ThreadPool.QueueUserWorkItem``: the call runs in a copy of the caller's
454
+ ``contextvars`` context, so it sees the caller's ``AsyncLocal`` values, and changes
455
+ made inside never reach the caller. Costs one context copy more than
456
+ ``queue``. Exceptions and ``prefer_local`` behave as there.
457
+ """
458
+ return _task._queue_work_item(callback, state, flow_context=True)
459
+
460
+
386
461
  class SemaphoreFullError(Exception):
387
462
  """Raised when ``release`` would exceed the maximum count (.NET ``SemaphoreFullException``)."""
388
463
 
File without changes
File without changes
File without changes
File without changes
File without changes