flpit 0.4.2.dev4__tar.gz → 0.4.2.dev6__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.dev4 → flpit-0.4.2.dev6}/PKG-INFO +1 -1
  2. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/pyproject.toml +1 -1
  3. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/task.py +183 -49
  4. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/threading.py +15 -1
  5. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/.gitignore +0 -0
  6. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/LICENSE +0 -0
  7. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/README.md +0 -0
  8. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flp/__init__.py +0 -0
  9. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/__init__.py +0 -0
  10. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/channels.py +0 -0
  11. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/concurrent.py +0 -0
  12. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/__init__.py +0 -0
  13. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/_grouping.py +0 -0
  14. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/_index.py +0 -0
  15. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/_join.py +0 -0
  16. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/_lookup.py +0 -0
  17. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/_zip.py +0 -0
  18. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/async_linq.py +0 -0
  19. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/comparers.py +0 -0
  20. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/core/linq.py +0 -0
  21. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/csv.py +0 -0
  22. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/flp.py +0 -0
  23. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/json/__init__.py +0 -0
  24. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/json/_core.py +0 -0
  25. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/json/_msgspec.py +0 -0
  26. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/src/flpit/json/_native.py +0 -0
  27. {flpit-0.4.2.dev4 → flpit-0.4.2.dev6}/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.dev4
3
+ Version: 0.4.2.dev6
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.dev4"
3
+ version = "0.4.2.dev6"
4
4
  description = "Fluent LINQ for Python — flip your iterables"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -421,6 +421,9 @@ class _TimerQueue:
421
421
  break
422
422
  if due:
423
423
  break
424
+ # Not while waiting: the next entry's callback references
425
+ # its task (a cancelled delay, say) until its deadline.
426
+ handle = callback = None
424
427
  if heap:
425
428
  condition.wait(min(heap[0][0] - now, park))
426
429
  else:
@@ -431,6 +434,7 @@ class _TimerQueue:
431
434
  except BaseException:
432
435
  _LOG.exception("Unhandled exception in Task timer callback")
433
436
  due.clear()
437
+ callback = None # the last one ran: do not keep its task while waiting
434
438
 
435
439
 
436
440
  def _fresh_context() -> dict[str, Any]:
@@ -765,6 +769,46 @@ class _WaitTask(_Operation):
765
769
  )
766
770
 
767
771
 
772
+ #: asyncio's ``_get_running_loop`` once asyncio is imported (C-accelerated; None instead of raising).
773
+ _asyncio_get_running_loop: Callable[[], Any] | None = None
774
+
775
+
776
+ def _asyncio_running_loop() -> Any:
777
+ """The asyncio event loop running on this thread, or None.
778
+
779
+ Costs one C call once asyncio is imported; before that no loop can be running, and a dict
780
+ lookup is all it takes. Unlike ``asyncio.get_running_loop()`` it never raises, so asking on
781
+ a flpit worker costs about 16 ns instead of ~150-190 ns for a raised and caught exception.
782
+ """
783
+ global _asyncio_get_running_loop
784
+ get_running_loop = _asyncio_get_running_loop
785
+ if get_running_loop is None:
786
+ events = sys.modules.get("asyncio.events")
787
+ if events is None:
788
+ return None
789
+ get_running_loop = _asyncio_get_running_loop = events._get_running_loop
790
+ return get_running_loop()
791
+
792
+
793
+ def _notify_asyncio_future(loop: Any, future: Any, completed: Task[Any]) -> None:
794
+ """Continuation of a Task awaited from asyncio: resolve ``future`` on its loop."""
795
+ try:
796
+ loop.call_soon_threadsafe(_complete_asyncio_future, future, completed)
797
+ except RuntimeError:
798
+ pass # the loop is closed: nobody is left to resume
799
+
800
+
801
+ def _complete_asyncio_future(future: Any, completed: Task[Any]) -> None:
802
+ """Runs on the asyncio loop: pass the task's outcome to the future its waiter awaits."""
803
+ if future.done():
804
+ return # the waiter was cancelled and the future with it
805
+ error = completed._error_to_raise()
806
+ if error is None:
807
+ future.set_result(completed._result)
808
+ else:
809
+ future.set_exception(error)
810
+
811
+
768
812
  def _resume_from(waiter: "Task[Any]", completed: "Task[Any]") -> None:
769
813
  """Store the outcome of ``completed`` as the next value sent into ``waiter``.
770
814
 
@@ -1107,7 +1151,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1107
1151
  task._run_coroutine_inline(state, work, args, kwargs)
1108
1152
  else:
1109
1153
  runtime._submit_inline(task, work, args, kwargs, state)
1110
- return task
1154
+ try:
1155
+ return task
1156
+ finally:
1157
+ del task, work, args, kwargs # see _release_frame
1111
1158
 
1112
1159
  @classmethod
1113
1160
  def _create(
@@ -1360,7 +1407,14 @@ class Task(Generic[T], metaclass=_TaskMeta):
1360
1407
  """
1361
1408
  if self._state is _PENDING:
1362
1409
  self._wait()
1363
- return self._raise_or_return()
1410
+ error = self._error_to_raise()
1411
+ if error is None:
1412
+ return cast(T, self._result)
1413
+ del self # see _release_frame
1414
+ try:
1415
+ raise error
1416
+ finally:
1417
+ del error
1364
1418
 
1365
1419
  # ------------------------------------------------------------------
1366
1420
  # Blocking waits (.NET Task.Wait / Task.WaitAll / Task.WaitAny)
@@ -1552,7 +1606,12 @@ class Task(Generic[T], metaclass=_TaskMeta):
1552
1606
  if self._state is _PENDING:
1553
1607
  self._wait()
1554
1608
  if self._state is _CANCELLED:
1555
- raise self._cancellation_exception()
1609
+ error = self._cancellation_exception()
1610
+ del self # see _release_frame
1611
+ try:
1612
+ raise error
1613
+ finally:
1614
+ del error
1556
1615
  return self._exception
1557
1616
 
1558
1617
  def _wait(self) -> None:
@@ -1570,6 +1629,9 @@ class Task(Generic[T], metaclass=_TaskMeta):
1570
1629
  and state.inline < _MAX_INLINE_DEPTH
1571
1630
  ):
1572
1631
  self._run_inline(state)
1632
+ if self._state is not _PENDING:
1633
+ del self # see _release_frame
1634
+ return
1573
1635
  with self._lock:
1574
1636
  if self._state is not _PENDING:
1575
1637
  return
@@ -1598,6 +1660,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1598
1660
  self._start()
1599
1661
  finally:
1600
1662
  _exit_inline(state, tail, hooks)
1663
+ del self # see _release_frame
1601
1664
 
1602
1665
  def _run_coroutine_inline(
1603
1666
  self, state: _ThreadState, target: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
@@ -1645,6 +1708,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1645
1708
  depth = state.inline
1646
1709
  state.inline = depth + 1
1647
1710
  drove = False
1711
+ coroutine: Any = None
1648
1712
  try:
1649
1713
  context.run(_current_task._value.set, self)
1650
1714
  try:
@@ -1696,6 +1760,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1696
1760
  _exit_inline_slot(state, tail)
1697
1761
  if hooks is not None:
1698
1762
  sys.set_asyncgen_hooks(*hooks)
1763
+ del self, context, target, args, kwargs, coroutine # see _release_frame
1699
1764
 
1700
1765
  def _add_continuation(self, continuation: Callable[[Task[Any]], Any]) -> bool:
1701
1766
  """Call ``continuation(self)`` on completion; False if already complete.
@@ -1728,52 +1793,87 @@ class Task(Generic[T], metaclass=_TaskMeta):
1728
1793
 
1729
1794
  def _await_pure_flpit_task(self) -> Generator[Any, T, T]:
1730
1795
  if self._state is not _PENDING:
1731
- return self._raise_or_return()
1732
- result = yield _WaitTask(self._runtime, self)
1733
- return result
1796
+ error = self._error_to_raise()
1797
+ if error is None:
1798
+ return cast(T, self._result)
1799
+ del self # see _release_frame
1800
+ try:
1801
+ raise error
1802
+ finally:
1803
+ del error
1804
+ operation = _WaitTask(self._runtime, self)
1805
+ del self # see _release_frame
1806
+ try:
1807
+ return (yield operation)
1808
+ finally:
1809
+ del operation
1734
1810
 
1735
1811
  __await__ = _await_pure_flpit_task
1736
1812
 
1737
1813
  def _await_asyncio_interop(self) -> Generator[Any, T, T]:
1738
- if self._state is not _PENDING:
1739
- return self._raise_or_return()
1814
+ """``__await__`` that also works inside asyncio coroutines (``Task.asyncio_interop``).
1740
1815
 
1741
- if "asyncio" in sys.modules:
1742
- import asyncio
1816
+ Awaited by flpit, it is the pure path plus one question, asked only while the task is
1817
+ still pending: is an asyncio loop running on this thread? That is one C call (asyncio's
1818
+ ``_get_running_loop``, which returns None instead of raising), or a dict lookup while
1819
+ asyncio isn't imported at all (see _asyncio_running_loop).
1743
1820
 
1821
+ Inside asyncio, the task's completion resolves an asyncio future on that loop. Neither the
1822
+ frame nor the callbacks keep the task (see _release_frame): a failed task awaited from
1823
+ asyncio is freed by reference counting too.
1824
+ """
1825
+ if self._state is not _PENDING:
1826
+ error = self._error_to_raise()
1827
+ if error is None:
1828
+ return cast(T, self._result)
1829
+ del self # see _release_frame
1744
1830
  try:
1745
- loop = asyncio.get_running_loop()
1746
- except RuntimeError:
1747
- pass
1748
- else:
1749
- future: asyncio.Future[T] = loop.create_future()
1750
-
1751
- def complete_future() -> None:
1752
- if future.done():
1753
- return
1754
-
1755
- try:
1756
- result = self._raise_or_return()
1757
- except BaseException as exc:
1758
- future.set_exception(exc)
1759
- else:
1760
- future.set_result(result)
1761
-
1762
- def notify(_: Task[Any]) -> None:
1763
- try:
1764
- loop.call_soon_threadsafe(complete_future)
1765
- except RuntimeError:
1766
- pass
1767
-
1768
- if not self._add_continuation(notify):
1769
- notify(self)
1770
-
1771
- return (
1772
- yield from cast(Generator[Any, T, T], future.__await__())
1773
- )
1774
-
1775
- result = yield _WaitTask(self._runtime, self)
1776
- return result
1831
+ raise error
1832
+ finally:
1833
+ del error
1834
+ loop = _asyncio_running_loop()
1835
+ if loop is None:
1836
+ operation = _WaitTask(self._runtime, self)
1837
+ del self # see _release_frame
1838
+ try:
1839
+ return (yield operation)
1840
+ finally:
1841
+ del operation
1842
+ future = loop.create_future()
1843
+ # No closures: the task's continuation must stay valid after this frame is gone
1844
+ # (an asyncio waiter can be cancelled while the task still runs).
1845
+ notify = functools.partial(_notify_asyncio_future, loop, future)
1846
+ if not self._add_continuation(notify):
1847
+ notify(self)
1848
+ del self, notify # see _release_frame
1849
+ try:
1850
+ return (yield from cast(Generator[Any, T, T], future.__await__()))
1851
+ finally:
1852
+ del future
1853
+
1854
+ # On by default: awaited by flpit code it costs about 0.1 µs (see _await_asyncio_interop).
1855
+ __await__ = _await_asyncio_interop
1856
+
1857
+ def _error_to_raise(self) -> BaseException | None:
1858
+ """The exception that awaiting this completed task raises; None if it succeeded.
1859
+
1860
+ _release_frame: a failed task's exception keeps its traceback, and the
1861
+ traceback keeps the frames it passed through, with their locals, even
1862
+ after those functions returned (and, through each frame's caller, the
1863
+ frames below them). A runtime frame that still held the task there
1864
+ would tie the task, its exception and every object in those frames into
1865
+ a cycle that only the cyclic garbage collector frees. So the runtime's
1866
+ frames on such a path delete their references to the task (``del
1867
+ self``) before they raise or return.
1868
+ """
1869
+ state = self._state
1870
+ if state is _SUCCEEDED:
1871
+ return None
1872
+ if state is _CANCELLED:
1873
+ return self._cancellation_exception()
1874
+ if state is _FAILED:
1875
+ return self._exception
1876
+ return InvalidStateError(f"{self.name} has not completed")
1777
1877
 
1778
1878
  def _raise_or_return(self) -> T:
1779
1879
  state = self._state
@@ -1917,7 +2017,16 @@ class Task(Generic[T], metaclass=_TaskMeta):
1917
2017
  else:
1918
2018
  self._sync_running = True
1919
2019
  try:
1920
- value = _run_with_context(context, target, *args, **kwargs)
2020
+ if _context_flow._notifications_enabled:
2021
+ value = _run_with_context(context, target, *args, **kwargs)
2022
+ else:
2023
+ # Inlined (see _drive): no extra frame between the
2024
+ # function and this one in a traceback.
2025
+ try:
2026
+ value = context.run(target, *args, **kwargs)
2027
+ finally:
2028
+ if _context_flow._notifications_enabled:
2029
+ _notify_context_exit(context)
1921
2030
  finally:
1922
2031
  self._sync_running = False
1923
2032
  state.tail = True
@@ -1935,11 +2044,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
1935
2044
  state.tail = True
1936
2045
  self._finish(_CANCELLED, exception=error)
1937
2046
  self._execution_context = None # break the cycle with the context
2047
+ del self, context, target, args, kwargs, work # see _release_frame
1938
2048
  return
1939
2049
  except BaseException as error:
1940
2050
  state.tail = True
1941
2051
  self._finish(_FAILED, exception=error)
1942
2052
  self._execution_context = None # break the cycle with the context
2053
+ del self, context, target, args, kwargs, work # see _release_frame
1943
2054
  return
1944
2055
 
1945
2056
  self._coroutine = coroutine
@@ -1947,7 +2058,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1947
2058
  # A synchronous function that returned an awaitable after the
1948
2059
  # shutdown sweep: it missed the cancellation request.
1949
2060
  self._cancel_requested = True
1950
- self._drive()
2061
+ try:
2062
+ self._drive()
2063
+ finally:
2064
+ del self, context, target, args, kwargs, work, coroutine, value # see _release_frame
1951
2065
 
1952
2066
  def _drive(self) -> None:
1953
2067
  """Run coroutine steps until the task parks, yields or completes."""
@@ -1958,6 +2072,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
1958
2072
  while True:
1959
2073
  value: Any = None
1960
2074
  error: BaseException | None = None
2075
+ # The previous step's operation references what the task waited on.
2076
+ yielded: Any = None
1961
2077
  with lock:
1962
2078
  coroutine = self._coroutine
1963
2079
  alive = self._state is _PENDING
@@ -2008,20 +2124,25 @@ class Task(Generic[T], metaclass=_TaskMeta):
2008
2124
  self._coroutine = None
2009
2125
  self._finish(_SUCCEEDED, result=stop.value)
2010
2126
  self._execution_context = None # break the cycle with the context
2127
+ del self, context, coroutine, value, error, yielded # see _release_frame
2011
2128
  return
2012
2129
  except OperationCanceledError as cancellation:
2013
2130
  state.tail = True
2014
2131
  self._coroutine = None
2015
2132
  self._finish(_CANCELLED, exception=cancellation)
2016
2133
  self._execution_context = None # break the cycle with the context
2134
+ del self, context, coroutine, value, error, yielded # see _release_frame
2017
2135
  return
2018
2136
  except BaseException as failure:
2019
2137
  state.tail = True
2020
2138
  self._coroutine = None
2021
2139
  self._finish(_FAILED, exception=failure)
2022
2140
  self._execution_context = None # break the cycle with the context
2141
+ del self, context, coroutine, value, error, yielded # see _release_frame
2023
2142
  return
2024
2143
 
2144
+ # Delivered: a caught exception must not stay in this frame.
2145
+ value = error = None
2025
2146
  state.tail = True
2026
2147
  try:
2027
2148
  resume = runtime._suspend(self, yielded)
@@ -3491,6 +3612,7 @@ class _Runtime:
3491
3612
  _close_if_coroutine(work)
3492
3613
  raise
3493
3614
  task._run_inline(state)
3615
+ del task, work, args, kwargs # see _release_frame
3494
3616
 
3495
3617
  def _submit_long_running(
3496
3618
  self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
@@ -3756,24 +3878,36 @@ class _Runtime:
3756
3878
 
3757
3879
 
3758
3880
  def _queue_work_item(callback: Any, state: Any, *, flow_context: bool) -> bool:
3759
- """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task."""
3881
+ """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task.
3882
+
3883
+ ``ThreadPool.queue`` has its own inlined copy of the ``flow_context=False`` path:
3884
+ it runs on a server's dispatch thread for every request.
3885
+ """
3760
3886
  if callback is None:
3761
3887
  raise ArgumentNullError("callBack")
3762
3888
  if not callable(callback):
3763
3889
  raise TypeError("callback must be callable")
3764
3890
  runtime = _get_runtime()
3891
+ context: Context | None = None
3765
3892
  if flow_context:
3766
3893
  context = copy_context()
3767
3894
  if context.get(_current_task._value) is not None:
3768
3895
  # A work item is not part of the task that queued it.
3769
3896
  context.run(_current_task._value.set, None)
3770
- else:
3771
- context = Context()
3772
- runtime._post(functools.partial(_run_work_item, runtime, context, callback, state))
3897
+ if runtime._shutdown_requested or not runtime._pool.queue(
3898
+ functools.partial(_run_work_item, runtime, callback, state, context)
3899
+ ):
3900
+ raise RuntimeShutdownError("Task runtime is shutting down")
3773
3901
  return True
3774
3902
 
3775
3903
 
3776
- def _run_work_item(runtime: _Runtime, context: Context, callback: Callable[..., Any], state: Any) -> None:
3904
+ def _run_work_item(
3905
+ runtime: _Runtime, callback: Callable[..., Any], state: Any, context: Context | None = None
3906
+ ) -> None:
3907
+ """Run a work item; without a context of the caller's, in a fresh, empty one."""
3908
+ if context is None:
3909
+ # Created here, not on the queuing thread: one allocation less there.
3910
+ context = Context()
3777
3911
  try:
3778
3912
  if state is _NO_STATE:
3779
3913
  _run_with_context(context, callback)
@@ -8,6 +8,7 @@ import time as _time
8
8
  from collections.abc import Callable
9
9
  from contextvars import Context, ContextVar
10
10
  from dataclasses import dataclass
11
+ from functools import partial as _partial
11
12
  from datetime import timedelta
12
13
  from typing import TYPE_CHECKING, Any, Final, cast, overload
13
14
 
@@ -434,7 +435,20 @@ class ThreadPool:
434
435
  shared queue. Returns ``True``. Raises ``RuntimeShutdownError`` while the runtime
435
436
  is shutting down.
436
437
  """
437
- return _task._queue_work_item(callback, state, flow_context=False)
438
+ # _task._queue_work_item(callback, state, flow_context=False), inlined: a
439
+ # server's dispatch thread calls this for every request.
440
+ if callback is None:
441
+ raise ArgumentNullError("callBack")
442
+ if not callable(callback):
443
+ raise TypeError("callback must be callable")
444
+ runtime = _task._runtime
445
+ if runtime is None or runtime._closed:
446
+ runtime = _task._get_runtime()
447
+ if runtime._shutdown_requested or not runtime._pool.queue(
448
+ _partial(_task._run_work_item, runtime, callback, state)
449
+ ):
450
+ raise _task.RuntimeShutdownError("Task runtime is shutting down")
451
+ return True
438
452
 
439
453
  @overload
440
454
  @staticmethod
File without changes
File without changes
File without changes
File without changes
File without changes