flpit 0.4.2.dev1__tar.gz → 0.4.2.dev2__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.dev2}/PKG-INFO +1 -1
  2. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/pyproject.toml +1 -1
  3. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/task.py +438 -69
  4. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/threading.py +76 -1
  5. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/.gitignore +0 -0
  6. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/LICENSE +0 -0
  7. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/README.md +0 -0
  8. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flp/__init__.py +0 -0
  9. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/__init__.py +0 -0
  10. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/channels.py +0 -0
  11. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/concurrent.py +0 -0
  12. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/__init__.py +0 -0
  13. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/_grouping.py +0 -0
  14. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/_index.py +0 -0
  15. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/_join.py +0 -0
  16. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/_lookup.py +0 -0
  17. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/_zip.py +0 -0
  18. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/async_linq.py +0 -0
  19. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/comparers.py +0 -0
  20. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/core/linq.py +0 -0
  21. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/csv.py +0 -0
  22. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/flp.py +0 -0
  23. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/json/__init__.py +0 -0
  24. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/json/_core.py +0 -0
  25. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/json/_msgspec.py +0 -0
  26. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/src/flpit/json/_native.py +0 -0
  27. {flpit-0.4.2.dev1 → flpit-0.4.2.dev2}/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.dev2
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.dev2"
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
@@ -781,6 +783,13 @@ def _close_if_coroutine(value: Any) -> None:
781
783
  value.close()
782
784
 
783
785
 
786
+ # Result types of synchronous work that are never awaitable; checking for them
787
+ # first spares the comparatively slow inspect.isawaitable() for most results.
788
+ _NEVER_AWAITABLE: Final = frozenset(
789
+ {type(None), bool, int, float, complex, str, bytes, bytearray, tuple, list, dict, set, frozenset}
790
+ )
791
+
792
+
784
793
  async def _await_any(awaitable: Any) -> Any:
785
794
  return await awaitable
786
795
 
@@ -813,6 +822,28 @@ class Task(Generic[T], metaclass=_TaskMeta):
813
822
  """The options the task was created with (.NET ``Task.CreationOptions``)."""
814
823
  return self._creation_options
815
824
 
825
+ # Per-task state that most tasks never change. The defaults live on the class
826
+ # and a task only gets its own attribute when it assigns one: a Task is created
827
+ # for every unit of work, and each attribute stored in __init__ costs time.
828
+ _result: Any = None
829
+ _exception: BaseException | None = None
830
+ _continuations: list[Callable[[Task[Any]], Any]] | None = None
831
+ _done_event: threading.Event | None = None
832
+ _work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
833
+ _coroutine: Coroutine[Any, Any, Any] | None = None
834
+ _waiting_on: _Operation | None = None
835
+ _running: bool = False
836
+ _sync_running: bool = False
837
+ _next_value: Any = None
838
+ _next_exception: BaseException | None = None
839
+ _cancel_requested: bool = False
840
+ _token_registration: CancellationTokenRegistration | None = None
841
+ _timer: _TimerHandle | None = None
842
+ _pass_token: bool = False
843
+ _is_promise_task: bool = False
844
+ _name: str | None = None
845
+ async_state: Any = None
846
+
816
847
  def __init__(
817
848
  self,
818
849
  runtime: "_Runtime",
@@ -824,29 +855,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
824
855
  # Guards the state transition, the continuation list and parking.
825
856
  self._lock = threading.Lock()
826
857
  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
858
  # Promise-style tasks never run code and need no execution context.
832
859
  self._execution_context: Context | None = (
833
860
  copy_context() if capture_context else None
834
861
  )
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
862
  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
863
 
851
864
  @property
852
865
  def name(self) -> str:
@@ -980,7 +993,126 @@ class Task(Generic[T], metaclass=_TaskMeta):
980
993
  ``creation_options`` (.NET ``TaskFactory.StartNew``): ``LONG_RUNNING`` runs
981
994
  the work on a dedicated thread instead of a pool worker, for work that
982
995
  blocks for a long time; see ``TaskCreationOptions`` for the others.
996
+
997
+ The work always starts on the pool, never on the calling thread; use
998
+ ``Task.run_inline`` to start it on the calling thread instead.
983
999
  """
1000
+ task = cls._create(work, args, kwargs, token, pass_token, creation_options)
1001
+ if creation_options and creation_options & _LONG_RUNNING:
1002
+ task._runtime._submit_long_running(task, work, args, kwargs)
1003
+ else:
1004
+ task._runtime._submit(task, work, args, kwargs)
1005
+ return task
1006
+
1007
+ @overload
1008
+ @classmethod
1009
+ def run_inline[R](
1010
+ cls,
1011
+ work: Callable[..., Coroutine[Any, Any, R]],
1012
+ /,
1013
+ *args: Any,
1014
+ token: CancellationToken | None = None,
1015
+ pass_token: bool = False,
1016
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1017
+ **kwargs: Any,
1018
+ ) -> Task[R]: ...
1019
+
1020
+ @overload
1021
+ @classmethod
1022
+ def run_inline[R](
1023
+ cls,
1024
+ work: Coroutine[Any, Any, R],
1025
+ /,
1026
+ *,
1027
+ token: CancellationToken | None = None,
1028
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1029
+ ) -> Task[R]: ...
1030
+
1031
+ @overload
1032
+ @classmethod
1033
+ def run_inline[R](
1034
+ cls,
1035
+ work: Callable[..., R],
1036
+ /,
1037
+ *args: Any,
1038
+ token: CancellationToken | None = None,
1039
+ pass_token: bool = False,
1040
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1041
+ **kwargs: Any,
1042
+ ) -> Task[R]: ...
1043
+
1044
+ @classmethod
1045
+ def run_inline(
1046
+ cls,
1047
+ work: Any,
1048
+ /,
1049
+ *args: Any,
1050
+ token: CancellationToken | None = None,
1051
+ pass_token: bool = False,
1052
+ creation_options: TaskCreationOptions = TaskCreationOptions.NONE,
1053
+ **kwargs: Any,
1054
+ ) -> Task[Any]:
1055
+ """Start ``work`` on the calling thread and return a Task for the rest of it.
1056
+
1057
+ This is how calling an ``async`` method behaves in .NET: the coroutine runs
1058
+ synchronously on the calling thread until its first ``await`` of something that
1059
+ has not completed yet. Only then does the caller get control back, holding a
1060
+ pending Task; after that point the coroutine resumes on the pool, as with
1061
+ ``Task.run``. A coroutine that never really suspends has completed when this
1062
+ returns, without a queue hop or a wake-up. A synchronous callable runs to its
1063
+ end on the calling thread.
1064
+
1065
+ Accepts the same arguments as ``Task.run``: a coroutine object or other
1066
+ awaitable, or a callable with its arguments. In detail:
1067
+
1068
+ * **Exceptions** raised before the first suspension complete the returned Task
1069
+ (faulted, or canceled for ``OperationCanceledError``); they are not raised into
1070
+ the caller.
1071
+ * **Awaiting something already complete** continues at once, on the same thread.
1072
+ ``await Task.yield_now()`` is a real suspension: the rest runs on the pool.
1073
+ * **Context:** the work runs in a copy of the caller's ``contextvars`` context, so
1074
+ ``AsyncLocal`` changes made inside never reach the caller.
1075
+ * **Cancellation:** an already cancelled ``token`` gives a canceled Task without
1076
+ running anything, as with ``Task.run``.
1077
+ * **Nesting:** each nested inline start adds to the calling thread's stack. Past a
1078
+ fixed depth (shared with ``Task.result()``, which also runs tasks inline) the
1079
+ work is queued to the pool instead, as ``Task.run`` does. The runtime's own
1080
+ timer and IO threads never run user code: called there, it queues as well.
1081
+
1082
+ ``creation_options`` behave as in ``Task.run``, except ``LONG_RUNNING``, which asks
1083
+ for a dedicated thread and is rejected.
1084
+ """
1085
+ if creation_options and isinstance(creation_options, int) and creation_options & _LONG_RUNNING:
1086
+ _close_if_coroutine(work)
1087
+ raise ArgumentOutOfRangeError(
1088
+ "creationOptions", "LONG_RUNNING cannot be combined with Task.run_inline()."
1089
+ )
1090
+ task = cls._create(work, args, kwargs, token, pass_token, creation_options)
1091
+ runtime = task._runtime
1092
+ state = _thread_state
1093
+ if state.internal or state.inline >= _MAX_INLINE_DEPTH:
1094
+ runtime._submit(task, work, args, kwargs)
1095
+ return task
1096
+ kind = type(work)
1097
+ if kind is CoroutineType or (
1098
+ (kind is FunctionType or kind is MethodType) and _is_coroutine_function(work)
1099
+ ):
1100
+ task._run_coroutine_inline(state, work, args, kwargs)
1101
+ else:
1102
+ runtime._submit_inline(task, work, args, kwargs, state)
1103
+ return task
1104
+
1105
+ @classmethod
1106
+ def _create(
1107
+ cls,
1108
+ work: Any,
1109
+ args: tuple[Any, ...],
1110
+ kwargs: dict[str, Any],
1111
+ token: CancellationToken | None,
1112
+ pass_token: bool,
1113
+ creation_options: TaskCreationOptions,
1114
+ ) -> Task[Any]:
1115
+ """Validate ``Task.run`` arguments and create the (not yet submitted) task."""
984
1116
  kind = type(work)
985
1117
  is_coroutine = kind is CoroutineType
986
1118
  if kind is FunctionType or kind is MethodType:
@@ -1006,16 +1138,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
1006
1138
  if is_coroutine:
1007
1139
  cast(Any, work).close()
1008
1140
  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)
1141
+ task = cls(_get_runtime(), token=token)
1142
+ if pass_token:
1143
+ task._pass_token = True
1144
+ if creation_options:
1145
+ task._creation_options = TaskCreationOptions(creation_options)
1146
+ if creation_options & TaskCreationOptions.RUN_CONTINUATIONS_ASYNCHRONOUSLY:
1147
+ task._async_continuations = True
1019
1148
  return task
1020
1149
 
1021
1150
  @overload
@@ -1433,7 +1562,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1433
1562
  and pool is self._runtime._pool
1434
1563
  and state.inline < _MAX_INLINE_DEPTH
1435
1564
  ):
1436
- self._run_inline(state, pool)
1565
+ self._run_inline(state)
1437
1566
  with self._lock:
1438
1567
  if self._state is not _PENDING:
1439
1568
  return
@@ -1449,30 +1578,114 @@ class Task(Generic[T], metaclass=_TaskMeta):
1449
1578
  finally:
1450
1579
  pool._worker_unblocked()
1451
1580
 
1452
- def _run_inline(self, state: _ThreadState, pool: "_WorkerPool") -> None:
1453
- """Start this task on the calling worker instead of waiting for it.
1581
+ def _run_inline(self, state: _ThreadState) -> None:
1582
+ """Start this task on the calling thread instead of on a pool worker.
1454
1583
 
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.
1584
+ Used by ``Task.result()`` for a task that has not started, and by
1585
+ ``Task.run_inline``. ``_start()`` takes the work under the task's
1586
+ lock, so either this thread or a worker that pops a queued item runs
1587
+ it, never both; the loser finds nothing to do.
1458
1588
  """
1459
- tail = state.tail
1460
- state.inline += 1
1589
+ tail, hooks = _enter_inline(state)
1461
1590
  try:
1462
1591
  self._start()
1463
1592
  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)
1593
+ _exit_inline(state, tail, hooks)
1594
+
1595
+ def _run_coroutine_inline(
1596
+ self, state: _ThreadState, target: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
1597
+ ) -> None:
1598
+ """``Task.run_inline`` of a coroutine: run its first step on the calling thread.
1599
+
1600
+ The same as ``_start()`` followed by ``_drive()``, minus what the first step
1601
+ of a task that nobody else has seen yet does not need. The task counts as
1602
+ running from the moment it is registered, so a concurrent shutdown treats it
1603
+ like any running coroutine: cancellation is delivered at its next step
1604
+ boundary. On the first suspension it is handed to the usual machinery.
1605
+ """
1606
+ runtime = self._runtime
1607
+ self._running = True
1608
+ try:
1609
+ runtime._track(self)
1610
+ except BaseException:
1611
+ _close_if_coroutine(target)
1612
+ raise
1613
+ token = self._token
1614
+ if token.is_cancellation_requested:
1615
+ _close_if_coroutine(target)
1616
+ self._finish(
1617
+ _CANCELLED,
1618
+ exception=OperationCanceledError(f"{self.name} cancelled before start", token=token),
1619
+ )
1620
+ return
1621
+
1622
+ context = cast(Context, self._execution_context)
1623
+ # The bookkeeping of _enter_inline()/_exit_inline(), spelled out: thread-local
1624
+ # attributes are slow, and a coroutine that finishes in its first step needs
1625
+ # few of them. ``tail`` stays False while the step runs (as in _drive), so
1626
+ # anything the step makes runnable goes to the shared queue directly.
1627
+ tail = state.tail
1628
+ if tail:
1629
+ state.tail = False
1630
+ pool = state.pool
1631
+ hooks = None
1632
+ if pool is None:
1633
+ hooks = sys.get_asyncgen_hooks()
1634
+ if hooks.firstiter is _asyncgen_firstiter:
1635
+ hooks = None
1636
+ else:
1637
+ _install_asyncgen_hooks()
1638
+ depth = state.inline
1639
+ state.inline = depth + 1
1640
+ drove = False
1641
+ try:
1642
+ context.run(_current_task._value.set, self)
1643
+ try:
1644
+ if type(target) is CoroutineType:
1645
+ coroutine = target
1646
+ else:
1647
+ if self._pass_token:
1648
+ kwargs = {**kwargs, "token": token}
1649
+ # Only creates the coroutine object; no user code runs yet.
1650
+ coroutine = context.run(target, *args, **kwargs)
1651
+ if _context_flow._notifications_enabled:
1652
+ yielded = _run_with_context(context, coroutine.send, None)
1653
+ else:
1654
+ try:
1655
+ yielded = context.run(coroutine.send, None)
1656
+ finally:
1657
+ if _context_flow._notifications_enabled:
1658
+ _notify_context_exit(context)
1659
+ except StopIteration as stop:
1660
+ self._finish(_SUCCEEDED, result=stop.value)
1661
+ return
1662
+ except OperationCanceledError as cancellation:
1663
+ self._finish(_CANCELLED, exception=cancellation)
1664
+ return
1665
+ except BaseException as failure:
1666
+ self._finish(_FAILED, exception=failure)
1667
+ return
1668
+
1669
+ # The first real suspension (or an await that _suspend resolves at once).
1670
+ drove = True
1671
+ state.tail = True
1672
+ self._coroutine = coroutine
1673
+ try:
1674
+ resume = runtime._suspend(self, yielded)
1675
+ except BaseException as failure:
1676
+ with self._lock:
1677
+ resume = self._running or self._waiting_on is yielded
1678
+ if resume:
1679
+ self._waiting_on = None
1680
+ self._next_exception = failure
1681
+ if resume:
1682
+ self._drive()
1683
+ finally:
1684
+ state.inline = depth
1685
+ if tail or drove:
1686
+ _exit_inline_slot(state, tail)
1687
+ if hooks is not None:
1688
+ sys.set_asyncgen_hooks(*hooks)
1476
1689
 
1477
1690
  def _add_continuation(self, continuation: Callable[[Task[Any]], Any]) -> bool:
1478
1691
  """Call ``continuation(self)`` on completion; False if already complete.
@@ -1577,17 +1790,24 @@ class Task(Generic[T], metaclass=_TaskMeta):
1577
1790
  with self._lock:
1578
1791
  if self._state is not _PENDING:
1579
1792
  return False
1580
- self._result = result
1581
- self._exception = exception
1793
+ # Fields still at their class default (None) are only read: storing
1794
+ # None would give every task an instance attribute of its own.
1795
+ if result is not None:
1796
+ self._result = result
1797
+ if exception is not None:
1798
+ self._exception = exception
1582
1799
  # Published last: lock-free readers check the state first.
1583
1800
  self._state = state
1584
1801
  continuations = self._continuations
1585
- self._continuations = None
1802
+ if continuations is not None:
1803
+ self._continuations = None
1586
1804
  event = self._done_event
1587
1805
  registration = self._token_registration
1588
- self._token_registration = None
1806
+ if registration is not None:
1807
+ self._token_registration = None
1589
1808
  timer = self._timer
1590
- self._timer = None
1809
+ if timer is not None:
1810
+ self._timer = None
1591
1811
  if registration is not None:
1592
1812
  registration.dispose()
1593
1813
  if timer is not None:
@@ -1673,9 +1893,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1673
1893
  # The context belongs to this task alone, so the current task is
1674
1894
  # set once instead of being set and restored around every step.
1675
1895
  context.run(_current_task._value.set, self)
1676
- if type(target) is CoroutineType:
1896
+ kind = type(target)
1897
+ if kind is CoroutineType:
1677
1898
  value = target
1678
- elif inspect.isawaitable(target):
1899
+ elif kind is not FunctionType and kind is not MethodType and inspect.isawaitable(target):
1679
1900
  value = _await_any(target)
1680
1901
  else:
1681
1902
  if self._pass_token:
@@ -1690,9 +1911,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1690
1911
  finally:
1691
1912
  self._sync_running = False
1692
1913
  state.tail = True
1693
- if type(value) is CoroutineType:
1914
+ kind = type(value)
1915
+ if kind is CoroutineType:
1694
1916
  coroutine = value
1695
- elif inspect.isawaitable(value):
1917
+ elif kind not in _NEVER_AWAITABLE and inspect.isawaitable(value):
1696
1918
  # Support sync wrappers that return an awaitable.
1697
1919
  coroutine = _await_any(value)
1698
1920
  else:
@@ -1730,8 +1952,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1730
1952
  self._running = True
1731
1953
  value = self._next_value
1732
1954
  error = self._next_exception
1733
- self._next_value = None
1734
- self._next_exception = None
1955
+ if value is not None:
1956
+ self._next_value = None
1957
+ if error is not None:
1958
+ self._next_exception = None
1735
1959
  if self._cancel_requested:
1736
1960
  self._cancel_requested = False
1737
1961
  if not isinstance(error, OperationCanceledError):
@@ -1748,10 +1972,24 @@ class Task(Generic[T], metaclass=_TaskMeta):
1748
1972
 
1749
1973
  state.tail = False
1750
1974
  try:
1751
- if error is None:
1752
- yielded = _run_with_context(context, coroutine.send, value)
1975
+ if _context_flow._notifications_enabled:
1976
+ if error is None:
1977
+ yielded = _run_with_context(context, coroutine.send, value)
1978
+ else:
1979
+ yielded = _run_with_context(context, coroutine.throw, error)
1753
1980
  else:
1754
- yielded = _run_with_context(context, coroutine.throw, error)
1981
+ # _run_with_context without AsyncLocal change handlers, inlined:
1982
+ # every step of every coroutine runs through here, and the
1983
+ # StopIteration that ends one is costly to pass through a frame.
1984
+ try:
1985
+ if error is None:
1986
+ yielded = context.run(coroutine.send, value)
1987
+ else:
1988
+ yielded = context.run(coroutine.throw, error)
1989
+ finally:
1990
+ if _context_flow._notifications_enabled:
1991
+ # A handler was installed while the step ran.
1992
+ _notify_context_exit(context)
1755
1993
  except StopIteration as stop:
1756
1994
  state.tail = True
1757
1995
  self._coroutine = None
@@ -3196,6 +3434,19 @@ class _Runtime:
3196
3434
  # If the pool closes in between, shutdown's final sweep cancels the task.
3197
3435
  self._pool.queue(task._start)
3198
3436
 
3437
+ def _submit_inline(
3438
+ self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any], state: _ThreadState
3439
+ ) -> None:
3440
+ """Task.run_inline: start the task on the calling thread right away."""
3441
+ task._work = (work, args, kwargs)
3442
+ try:
3443
+ self._track(task)
3444
+ except BaseException:
3445
+ task._work = None
3446
+ _close_if_coroutine(work)
3447
+ raise
3448
+ task._run_inline(state)
3449
+
3199
3450
  def _submit_long_running(
3200
3451
  self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
3201
3452
  ) -> None:
@@ -3459,6 +3710,81 @@ class _Runtime:
3459
3710
  return report
3460
3711
 
3461
3712
 
3713
+ def _queue_work_item(callback: Any, state: Any, *, flow_context: bool) -> bool:
3714
+ """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task."""
3715
+ if callback is None:
3716
+ raise ArgumentNullError("callBack")
3717
+ if not callable(callback):
3718
+ raise TypeError("callback must be callable")
3719
+ runtime = _get_runtime()
3720
+ if flow_context:
3721
+ context = copy_context()
3722
+ if context.get(_current_task._value) is not None:
3723
+ # A work item is not part of the task that queued it.
3724
+ context.run(_current_task._value.set, None)
3725
+ else:
3726
+ context = Context()
3727
+ runtime._post(functools.partial(_run_work_item, runtime, context, callback, state))
3728
+ return True
3729
+
3730
+
3731
+ def _run_work_item(runtime: _Runtime, context: Context, callback: Callable[..., Any], state: Any) -> None:
3732
+ try:
3733
+ if state is _NO_STATE:
3734
+ _run_with_context(context, callback)
3735
+ else:
3736
+ _run_with_context(context, callback, state)
3737
+ except BaseException as error:
3738
+ runtime._report_exception(
3739
+ {"message": "Unhandled exception in a thread-pool work item", "callback": callback}, error
3740
+ )
3741
+
3742
+
3743
+ def _enter_inline(state: _ThreadState) -> tuple[bool, Any]:
3744
+ """Bookkeeping before a task runs inline on the calling thread.
3745
+
3746
+ Returns what ``_exit_inline`` restores. Pool workers and LONG_RUNNING threads
3747
+ have flpit's async generator hooks; any other thread gets them for the time
3748
+ being, so that async generators the task starts are tracked as on the pool.
3749
+ """
3750
+ hooks = None
3751
+ if state.pool is None:
3752
+ hooks = sys.get_asyncgen_hooks()
3753
+ if hooks.firstiter is _asyncgen_firstiter:
3754
+ hooks = None
3755
+ else:
3756
+ _install_asyncgen_hooks()
3757
+ state.inline += 1
3758
+ return state.tail, hooks
3759
+
3760
+
3761
+ def _exit_inline(state: _ThreadState, tail: bool, hooks: Any) -> None:
3762
+ state.inline -= 1
3763
+ _exit_inline_slot(state, tail)
3764
+ if hooks is not None:
3765
+ sys.set_asyncgen_hooks(*hooks)
3766
+
3767
+
3768
+ def _exit_inline_slot(state: _ThreadState, tail: bool) -> None:
3769
+ # The caller is still inside its own work item. Anything the inlined task
3770
+ # left for "this worker's next item" must not wait until the caller
3771
+ # returns -- the caller may be about to block on exactly that. (Only pool
3772
+ # workers ever fill the slot.)
3773
+ state.tail = tail
3774
+ item = state.slot
3775
+ if item is not None:
3776
+ state.slot = None
3777
+ # False only if the pool closed, and then shutdown has already
3778
+ # cancelled the task behind the item.
3779
+ cast("_WorkerPool", state.pool).queue(item)
3780
+
3781
+
3782
+ def _is_coroutine_function(function: Any) -> bool:
3783
+ """True for an ``async def`` function or bound method, by its code flags alone."""
3784
+ code = getattr(function.__func__ if type(function) is MethodType else function, "__code__", None)
3785
+ return code is not None and bool(code.co_flags & inspect.CO_COROUTINE)
3786
+
3787
+
3462
3788
  def _is_async_callable(value: Any) -> bool:
3463
3789
  function = value.__func__ if type(value) is MethodType else value
3464
3790
  if type(function) is FunctionType:
@@ -3529,20 +3855,63 @@ if hasattr(os, "register_at_fork"):
3529
3855
  os.register_at_fork(after_in_child=_reset_after_fork)
3530
3856
 
3531
3857
 
3858
+ class _TaskDecorator(Protocol):
3859
+ """What ``task(inline=...)`` returns: the decorator itself."""
3860
+
3861
+ @overload
3862
+ def __call__[**P, T](self, function: Callable[P, Awaitable[T]], /) -> Callable[P, Task[T]]: ...
3863
+
3864
+ @overload
3865
+ def __call__[**P, T](self, function: Callable[P, T], /) -> Callable[P, Task[T]]: ...
3866
+
3867
+
3532
3868
  @overload
3533
3869
  def task[**P, T](
3534
- function: Callable[P, Awaitable[T]]
3870
+ function: Callable[P, Awaitable[T]], /
3535
3871
  ) -> Callable[P, Task[T]]: ...
3536
3872
 
3537
3873
  @overload
3538
3874
  def task[**P, T](
3539
- function: Callable[P, T]
3875
+ function: Callable[P, T], /
3540
3876
  ) -> Callable[P, Task[T]]: ...
3541
3877
 
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
3878
+ @overload
3879
+ def task(*, inline: bool = False) -> _TaskDecorator: ...
3880
+
3881
+ def task(function: Callable[..., Any] | None = None, /, *, inline: bool = False) -> Any:
3882
+ """Make every call of ``function`` start a Task and return it.
3883
+
3884
+ ``@task`` starts each call with ``Task.run``: queued to the pool, for plain and
3885
+ ``async def`` functions alike. That is .NET's ``Task.Run`` on every call.
3886
+
3887
+ ``@task(inline=True)`` is for ``async def`` functions only and starts each call with
3888
+ ``Task.run_inline``: the coroutine runs on the calling thread until its first
3889
+ ``await`` of something not yet complete, which is how calling an ``async`` method
3890
+ behaves in .NET. A plain function is rejected, because running it inline would just
3891
+ be calling it.
3545
3892
  """
3893
+ if function is None:
3894
+ def decorator(target: Callable[..., Any], /) -> Callable[..., Task[Any]]:
3895
+ return _task_wrapper(target, inline)
3896
+
3897
+ return decorator
3898
+ return _task_wrapper(function, inline)
3899
+
3900
+
3901
+ def _task_wrapper(function: Callable[..., Any], inline: bool) -> Callable[..., Task[Any]]:
3902
+ if inline:
3903
+ if not _is_async_callable(function):
3904
+ raise TypeError(
3905
+ "@task(inline=True) needs an async def function: a plain function started "
3906
+ "inline would simply run to its end at the call. Use @task for it."
3907
+ )
3908
+
3909
+ @wraps(function)
3910
+ def inline_wrapper(*args: Any, **kwargs: Any) -> Task[Any]:
3911
+ return Task.run_inline(function, *args, **kwargs)
3912
+
3913
+ return inline_wrapper
3914
+
3546
3915
  @wraps(function)
3547
3916
  def wrapper(*args: Any, **kwargs: Any) -> Task[Any]:
3548
3917
  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