flpit 0.4.2.dev3__tar.gz → 0.4.2.dev5__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.dev3 → flpit-0.4.2.dev5}/PKG-INFO +1 -1
  2. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/pyproject.toml +1 -1
  3. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/task.py +114 -38
  4. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/threading.py +15 -1
  5. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/.gitignore +0 -0
  6. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/LICENSE +0 -0
  7. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/README.md +0 -0
  8. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flp/__init__.py +0 -0
  9. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/__init__.py +0 -0
  10. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/channels.py +0 -0
  11. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/concurrent.py +0 -0
  12. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/__init__.py +0 -0
  13. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/_grouping.py +0 -0
  14. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/_index.py +0 -0
  15. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/_join.py +0 -0
  16. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/_lookup.py +0 -0
  17. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/_zip.py +0 -0
  18. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/async_linq.py +0 -0
  19. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/comparers.py +0 -0
  20. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/core/linq.py +0 -0
  21. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/csv.py +0 -0
  22. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/flp.py +0 -0
  23. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/json/__init__.py +0 -0
  24. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/json/_core.py +0 -0
  25. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/json/_msgspec.py +0 -0
  26. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/src/flpit/json/_native.py +0 -0
  27. {flpit-0.4.2.dev3 → flpit-0.4.2.dev5}/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.dev3
3
+ Version: 0.4.2.dev5
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.dev3"
3
+ version = "0.4.2.dev5"
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]:
@@ -859,9 +863,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
859
863
  # Promise-style tasks never run code and need no execution context.
860
864
  # The context holds this task as the current task, so the two form a
861
865
  # 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.
866
+ # drops the context: otherwise a finished task, its result and every
867
+ # AsyncLocal value set inside it would only be freed by the cyclic
868
+ # garbage collector. (A failed task still is: its exception's traceback
869
+ # reaches the runtime frames that ran it, as with any stored exception.)
865
870
  self._execution_context: Context | None = (
866
871
  copy_context() if capture_context else None
867
872
  )
@@ -1106,7 +1111,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1106
1111
  task._run_coroutine_inline(state, work, args, kwargs)
1107
1112
  else:
1108
1113
  runtime._submit_inline(task, work, args, kwargs, state)
1109
- return task
1114
+ try:
1115
+ return task
1116
+ finally:
1117
+ del task, work, args, kwargs # see _release_frame
1110
1118
 
1111
1119
  @classmethod
1112
1120
  def _create(
@@ -1359,7 +1367,14 @@ class Task(Generic[T], metaclass=_TaskMeta):
1359
1367
  """
1360
1368
  if self._state is _PENDING:
1361
1369
  self._wait()
1362
- return self._raise_or_return()
1370
+ error = self._error_to_raise()
1371
+ if error is None:
1372
+ return cast(T, self._result)
1373
+ del self # see _release_frame
1374
+ try:
1375
+ raise error
1376
+ finally:
1377
+ del error
1363
1378
 
1364
1379
  # ------------------------------------------------------------------
1365
1380
  # Blocking waits (.NET Task.Wait / Task.WaitAll / Task.WaitAny)
@@ -1551,7 +1566,12 @@ class Task(Generic[T], metaclass=_TaskMeta):
1551
1566
  if self._state is _PENDING:
1552
1567
  self._wait()
1553
1568
  if self._state is _CANCELLED:
1554
- raise self._cancellation_exception()
1569
+ error = self._cancellation_exception()
1570
+ del self # see _release_frame
1571
+ try:
1572
+ raise error
1573
+ finally:
1574
+ del error
1555
1575
  return self._exception
1556
1576
 
1557
1577
  def _wait(self) -> None:
@@ -1569,6 +1589,9 @@ class Task(Generic[T], metaclass=_TaskMeta):
1569
1589
  and state.inline < _MAX_INLINE_DEPTH
1570
1590
  ):
1571
1591
  self._run_inline(state)
1592
+ if self._state is not _PENDING:
1593
+ del self # see _release_frame
1594
+ return
1572
1595
  with self._lock:
1573
1596
  if self._state is not _PENDING:
1574
1597
  return
@@ -1597,6 +1620,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1597
1620
  self._start()
1598
1621
  finally:
1599
1622
  _exit_inline(state, tail, hooks)
1623
+ del self # see _release_frame
1600
1624
 
1601
1625
  def _run_coroutine_inline(
1602
1626
  self, state: _ThreadState, target: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
@@ -1644,6 +1668,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1644
1668
  depth = state.inline
1645
1669
  state.inline = depth + 1
1646
1670
  drove = False
1671
+ coroutine: Any = None
1647
1672
  try:
1648
1673
  context.run(_current_task._value.set, self)
1649
1674
  try:
@@ -1695,6 +1720,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
1695
1720
  _exit_inline_slot(state, tail)
1696
1721
  if hooks is not None:
1697
1722
  sys.set_asyncgen_hooks(*hooks)
1723
+ del self, context, target, args, kwargs, coroutine # see _release_frame
1698
1724
 
1699
1725
  def _add_continuation(self, continuation: Callable[[Task[Any]], Any]) -> bool:
1700
1726
  """Call ``continuation(self)`` on completion; False if already complete.
@@ -1727,9 +1753,20 @@ class Task(Generic[T], metaclass=_TaskMeta):
1727
1753
 
1728
1754
  def _await_pure_flpit_task(self) -> Generator[Any, T, T]:
1729
1755
  if self._state is not _PENDING:
1730
- return self._raise_or_return()
1731
- result = yield _WaitTask(self._runtime, self)
1732
- return result
1756
+ error = self._error_to_raise()
1757
+ if error is None:
1758
+ return cast(T, self._result)
1759
+ del self # see _release_frame
1760
+ try:
1761
+ raise error
1762
+ finally:
1763
+ del error
1764
+ operation = _WaitTask(self._runtime, self)
1765
+ del self # see _release_frame
1766
+ try:
1767
+ return (yield operation)
1768
+ finally:
1769
+ del operation
1733
1770
 
1734
1771
  __await__ = _await_pure_flpit_task
1735
1772
 
@@ -1771,8 +1808,33 @@ class Task(Generic[T], metaclass=_TaskMeta):
1771
1808
  yield from cast(Generator[Any, T, T], future.__await__())
1772
1809
  )
1773
1810
 
1774
- result = yield _WaitTask(self._runtime, self)
1775
- return result
1811
+ operation = _WaitTask(self._runtime, self)
1812
+ del self # see _release_frame
1813
+ try:
1814
+ return (yield operation)
1815
+ finally:
1816
+ del operation
1817
+
1818
+ def _error_to_raise(self) -> BaseException | None:
1819
+ """The exception that awaiting this completed task raises; None if it succeeded.
1820
+
1821
+ _release_frame: a failed task's exception keeps its traceback, and the
1822
+ traceback keeps the frames it passed through, with their locals, even
1823
+ after those functions returned (and, through each frame's caller, the
1824
+ frames below them). A runtime frame that still held the task there
1825
+ would tie the task, its exception and every object in those frames into
1826
+ a cycle that only the cyclic garbage collector frees. So the runtime's
1827
+ frames on such a path delete their references to the task (``del
1828
+ self``) before they raise or return.
1829
+ """
1830
+ state = self._state
1831
+ if state is _SUCCEEDED:
1832
+ return None
1833
+ if state is _CANCELLED:
1834
+ return self._cancellation_exception()
1835
+ if state is _FAILED:
1836
+ return self._exception
1837
+ return InvalidStateError(f"{self.name} has not completed")
1776
1838
 
1777
1839
  def _raise_or_return(self) -> T:
1778
1840
  state = self._state
@@ -1804,9 +1866,6 @@ class Task(Generic[T], metaclass=_TaskMeta):
1804
1866
  if result is not None:
1805
1867
  self._result = result
1806
1868
  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
1869
  self._exception = exception
1811
1870
  # Published last: lock-free readers check the state first.
1812
1871
  self._state = state
@@ -1919,7 +1978,16 @@ class Task(Generic[T], metaclass=_TaskMeta):
1919
1978
  else:
1920
1979
  self._sync_running = True
1921
1980
  try:
1922
- value = _run_with_context(context, target, *args, **kwargs)
1981
+ if _context_flow._notifications_enabled:
1982
+ value = _run_with_context(context, target, *args, **kwargs)
1983
+ else:
1984
+ # Inlined (see _drive): no extra frame between the
1985
+ # function and this one in a traceback.
1986
+ try:
1987
+ value = context.run(target, *args, **kwargs)
1988
+ finally:
1989
+ if _context_flow._notifications_enabled:
1990
+ _notify_context_exit(context)
1923
1991
  finally:
1924
1992
  self._sync_running = False
1925
1993
  state.tail = True
@@ -1937,11 +2005,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
1937
2005
  state.tail = True
1938
2006
  self._finish(_CANCELLED, exception=error)
1939
2007
  self._execution_context = None # break the cycle with the context
2008
+ del self, context, target, args, kwargs, work # see _release_frame
1940
2009
  return
1941
2010
  except BaseException as error:
1942
2011
  state.tail = True
1943
2012
  self._finish(_FAILED, exception=error)
1944
2013
  self._execution_context = None # break the cycle with the context
2014
+ del self, context, target, args, kwargs, work # see _release_frame
1945
2015
  return
1946
2016
 
1947
2017
  self._coroutine = coroutine
@@ -1949,7 +2019,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
1949
2019
  # A synchronous function that returned an awaitable after the
1950
2020
  # shutdown sweep: it missed the cancellation request.
1951
2021
  self._cancel_requested = True
1952
- self._drive()
2022
+ try:
2023
+ self._drive()
2024
+ finally:
2025
+ del self, context, target, args, kwargs, work, coroutine, value # see _release_frame
1953
2026
 
1954
2027
  def _drive(self) -> None:
1955
2028
  """Run coroutine steps until the task parks, yields or completes."""
@@ -1960,6 +2033,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
1960
2033
  while True:
1961
2034
  value: Any = None
1962
2035
  error: BaseException | None = None
2036
+ # The previous step's operation references what the task waited on.
2037
+ yielded: Any = None
1963
2038
  with lock:
1964
2039
  coroutine = self._coroutine
1965
2040
  alive = self._state is _PENDING
@@ -2010,20 +2085,25 @@ class Task(Generic[T], metaclass=_TaskMeta):
2010
2085
  self._coroutine = None
2011
2086
  self._finish(_SUCCEEDED, result=stop.value)
2012
2087
  self._execution_context = None # break the cycle with the context
2088
+ del self, context, coroutine, value, error, yielded # see _release_frame
2013
2089
  return
2014
2090
  except OperationCanceledError as cancellation:
2015
2091
  state.tail = True
2016
2092
  self._coroutine = None
2017
2093
  self._finish(_CANCELLED, exception=cancellation)
2018
2094
  self._execution_context = None # break the cycle with the context
2095
+ del self, context, coroutine, value, error, yielded # see _release_frame
2019
2096
  return
2020
2097
  except BaseException as failure:
2021
2098
  state.tail = True
2022
2099
  self._coroutine = None
2023
2100
  self._finish(_FAILED, exception=failure)
2024
2101
  self._execution_context = None # break the cycle with the context
2102
+ del self, context, coroutine, value, error, yielded # see _release_frame
2025
2103
  return
2026
2104
 
2105
+ # Delivered: a caught exception must not stay in this frame.
2106
+ value = error = None
2027
2107
  state.tail = True
2028
2108
  try:
2029
2109
  resume = runtime._suspend(self, yielded)
@@ -2111,23 +2191,6 @@ class Task(Generic[T], metaclass=_TaskMeta):
2111
2191
 
2112
2192
  _current_task: AsyncLocal[Task[Any] | None] = AsyncLocal()
2113
2193
 
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
-
2131
2194
 
2132
2195
  # ---------------------------------------------------------------------------
2133
2196
  # Async generators (PEP 525 hooks)
@@ -3510,6 +3573,7 @@ class _Runtime:
3510
3573
  _close_if_coroutine(work)
3511
3574
  raise
3512
3575
  task._run_inline(state)
3576
+ del task, work, args, kwargs # see _release_frame
3513
3577
 
3514
3578
  def _submit_long_running(
3515
3579
  self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
@@ -3775,24 +3839,36 @@ class _Runtime:
3775
3839
 
3776
3840
 
3777
3841
  def _queue_work_item(callback: Any, state: Any, *, flow_context: bool) -> bool:
3778
- """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task."""
3842
+ """``ThreadPool.queue`` / ``queue_user_work_item``: queue ``callback`` without a Task.
3843
+
3844
+ ``ThreadPool.queue`` has its own inlined copy of the ``flow_context=False`` path:
3845
+ it runs on a server's dispatch thread for every request.
3846
+ """
3779
3847
  if callback is None:
3780
3848
  raise ArgumentNullError("callBack")
3781
3849
  if not callable(callback):
3782
3850
  raise TypeError("callback must be callable")
3783
3851
  runtime = _get_runtime()
3852
+ context: Context | None = None
3784
3853
  if flow_context:
3785
3854
  context = copy_context()
3786
3855
  if context.get(_current_task._value) is not None:
3787
3856
  # A work item is not part of the task that queued it.
3788
3857
  context.run(_current_task._value.set, None)
3789
- else:
3790
- context = Context()
3791
- runtime._post(functools.partial(_run_work_item, runtime, context, callback, state))
3858
+ if runtime._shutdown_requested or not runtime._pool.queue(
3859
+ functools.partial(_run_work_item, runtime, callback, state, context)
3860
+ ):
3861
+ raise RuntimeShutdownError("Task runtime is shutting down")
3792
3862
  return True
3793
3863
 
3794
3864
 
3795
- def _run_work_item(runtime: _Runtime, context: Context, callback: Callable[..., Any], state: Any) -> None:
3865
+ def _run_work_item(
3866
+ runtime: _Runtime, callback: Callable[..., Any], state: Any, context: Context | None = None
3867
+ ) -> None:
3868
+ """Run a work item; without a context of the caller's, in a fresh, empty one."""
3869
+ if context is None:
3870
+ # Created here, not on the queuing thread: one allocation less there.
3871
+ context = Context()
3796
3872
  try:
3797
3873
  if state is _NO_STATE:
3798
3874
  _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