param 2.4.2rc0__tar.gz → 2.4.2rc1__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 (75) hide show
  1. {param-2.4.2rc0 → param-2.4.2rc1}/PKG-INFO +1 -1
  2. {param-2.4.2rc0 → param-2.4.2rc1}/param/_version.py +2 -2
  3. {param-2.4.2rc0 → param-2.4.2rc1}/param/parameterized.py +70 -14
  4. {param-2.4.2rc0 → param-2.4.2rc1}/param/reactive.py +97 -22
  5. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testreactive.py +254 -0
  6. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testrefs.py +49 -0
  7. {param-2.4.2rc0 → param-2.4.2rc1}/.gitignore +0 -0
  8. {param-2.4.2rc0 → param-2.4.2rc1}/LICENSE.txt +0 -0
  9. {param-2.4.2rc0 → param-2.4.2rc1}/README.md +0 -0
  10. {param-2.4.2rc0 → param-2.4.2rc1}/numbergen/__init__.py +0 -0
  11. {param-2.4.2rc0 → param-2.4.2rc1}/param/__init__.py +0 -0
  12. {param-2.4.2rc0 → param-2.4.2rc1}/param/_utils.py +0 -0
  13. {param-2.4.2rc0 → param-2.4.2rc1}/param/depends.py +0 -0
  14. {param-2.4.2rc0 → param-2.4.2rc1}/param/display.py +0 -0
  15. {param-2.4.2rc0 → param-2.4.2rc1}/param/ipython.py +0 -0
  16. {param-2.4.2rc0 → param-2.4.2rc1}/param/mypy_plugin.py +0 -0
  17. {param-2.4.2rc0 → param-2.4.2rc1}/param/parameters.py +0 -0
  18. {param-2.4.2rc0 → param-2.4.2rc1}/param/py.typed +0 -0
  19. {param-2.4.2rc0 → param-2.4.2rc1}/param/serializer.py +0 -0
  20. {param-2.4.2rc0 → param-2.4.2rc1}/param/version.py +0 -0
  21. {param-2.4.2rc0 → param-2.4.2rc1}/pyproject.toml +0 -0
  22. {param-2.4.2rc0 → param-2.4.2rc1}/tests/__init__.py +0 -0
  23. {param-2.4.2rc0 → param-2.4.2rc1}/tests/assert_types.py +0 -0
  24. {param-2.4.2rc0 → param-2.4.2rc1}/tests/conftest.py +0 -0
  25. {param-2.4.2rc0 → param-2.4.2rc1}/tests/pyrightconfig-bare.json +0 -0
  26. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testaddparameter.py +0 -0
  27. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testbind.py +0 -0
  28. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testbooleanparam.py +0 -0
  29. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testbytesparam.py +0 -0
  30. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcalendardateparam.py +0 -0
  31. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcalendardaterangeparam.py +0 -0
  32. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcallable.py +0 -0
  33. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testclassselector.py +0 -0
  34. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcolorparameter.py +0 -0
  35. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcomparator.py +0 -0
  36. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcompositeparams.py +0 -0
  37. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testcustomparam.py +0 -0
  38. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdateparam.py +0 -0
  39. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdaterangeparam.py +0 -0
  40. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdefaultfactory.py +0 -0
  41. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdefaults.py +0 -0
  42. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdeprecations.py +0 -0
  43. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testdynamicparams.py +0 -0
  44. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testfiledeserialization.py +0 -0
  45. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testfileselector.py +0 -0
  46. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testimports.py +0 -0
  47. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testipythonmagic.py +0 -0
  48. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testjsonserialization.py +0 -0
  49. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testlist.py +0 -0
  50. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testlistselector.py +0 -0
  51. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testmultifileselector.py +0 -0
  52. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testnumbergen.py +0 -0
  53. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testnumberparameter.py +0 -0
  54. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testnumpy.py +0 -0
  55. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testobjectselector.py +0 -0
  56. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testpandas.py +0 -0
  57. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparamdepends.py +0 -0
  58. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparameter.py +0 -0
  59. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparameterizedobject.py +0 -0
  60. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparameterizedrepr.py +0 -0
  61. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparamoutput.py +0 -0
  62. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testparamunion.py +0 -0
  63. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testpathparam.py +0 -0
  64. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testpickle.py +0 -0
  65. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testrangeparameter.py +0 -0
  66. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testreprhtml.py +0 -0
  67. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testselector.py +0 -0
  68. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testsignatures.py +0 -0
  69. {param-2.4.2rc0 → param-2.4.2rc1}/tests/teststringparam.py +0 -0
  70. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testtimedependent.py +0 -0
  71. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testtupleparam.py +0 -0
  72. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testutils.py +0 -0
  73. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testversion.py +0 -0
  74. {param-2.4.2rc0 → param-2.4.2rc1}/tests/testwatch.py +0 -0
  75. {param-2.4.2rc0 → param-2.4.2rc1}/tests/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: param
3
- Version: 2.4.2rc0
3
+ Version: 2.4.2rc1
4
4
  Summary: Declarative parameters for robust Python classes and a rich API for reactive programming
5
5
  Project-URL: Homepage, https://param.holoviz.org/
6
6
  Project-URL: Tracker, https://github.com/holoviz/param/issues
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '2.4.2rc0'
22
- __version_tuple__ = version_tuple = (2, 4, 2, 'rc0')
21
+ __version__ = version = '2.4.2rc1'
22
+ __version_tuple__ = version_tuple = (2, 4, 2, 'rc1')
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -2579,10 +2579,11 @@ class Parameters:
2579
2579
 
2580
2580
  ns_type = type(self_)
2581
2581
 
2582
- # The cached parameters are read from _param__private directly rather
2583
- # than via the _cls_parameters property. If that property raised an
2584
- # AttributeError we would be called to handle it and recurse, so it is
2585
- # only invoked as a descriptor, i.e. without attribute lookup on self_.
2582
+ # Read the cached parameters from _param__private rather than from the
2583
+ # _cls_parameters property: an AttributeError raised by that property is
2584
+ # dispatched to this method, so accessing it as an attribute here would
2585
+ # recurse. When the cache is empty the property is invoked directly as a
2586
+ # descriptor instead, which bypasses that dispatch.
2586
2587
  params = cls._param__private.params
2587
2588
  if not params:
2588
2589
  params = _find_descriptor(ns_type, '_cls_parameters').__get__(self_, ns_type)
@@ -2742,7 +2743,10 @@ class Parameters:
2742
2743
  if new_val is Skip or new_val is Undefined:
2743
2744
  continue
2744
2745
  elif is_async:
2745
- async_executor(partial(self_._async_ref, pname, t.cast("t.Awaitable[t.Any]", new_val)))
2746
+ generation = self_._schedule_async_ref(pname)
2747
+ async_executor(partial(
2748
+ self_._async_ref, pname, t.cast("t.Awaitable[t.Any]", new_val), generation
2749
+ ))
2746
2750
  continue
2747
2751
 
2748
2752
  updates[pname] = new_val
@@ -2763,39 +2767,85 @@ class Parameters:
2763
2767
  except Skip:
2764
2768
  value = Undefined
2765
2769
  if is_async and pobj.name:
2766
- async_executor(partial(self_._async_ref, pobj.name, t.cast("t.Awaitable[t.Any]", value)))
2770
+ generation = self_._schedule_async_ref(pobj.name)
2771
+ async_executor(partial(
2772
+ self_._async_ref, pobj.name, t.cast("t.Awaitable[t.Any]", value), generation
2773
+ ))
2767
2774
  value = None
2768
2775
  return ref, deps, value, is_async
2769
2776
 
2770
- async def _async_ref(self_, pname: str, awaitable: t.Awaitable[t.Any]):
2777
+ def _schedule_async_ref(self_, pname: str) -> int:
2778
+ """
2779
+ Record that an asynchronous reference resolution is about to be
2780
+ scheduled and return the generation identifying it.
2781
+
2782
+ The generation is bumped synchronously, before the task is handed to
2783
+ the executor, so that the reference reads as unsettled from the moment
2784
+ it is superseded rather than only once the task starts running.
2785
+ """
2786
+ if self_.self is None:
2787
+ return 0
2788
+ private = self_.self._param__private
2789
+ private.async_ref_scheduled[pname] += 1
2790
+ return private.async_ref_scheduled[pname]
2791
+
2792
+ def _settle_async_ref(self_, pname: str, generation: int):
2793
+ """
2794
+ Record that the resolution identified by ``generation`` produced a
2795
+ value, or gave up on producing one.
2796
+
2797
+ A superseded task settling late must not mark the reference settled for
2798
+ the generation that superseded it, so the generation is recorded rather
2799
+ than cleared. Generators settle on every value they yield, so a
2800
+ reference is unsettled only until its next value arrives, not until the
2801
+ generator is exhausted.
2802
+ """
2803
+ if self_.self is None or not generation:
2804
+ return
2805
+ settled = self_.self._param__private.async_ref_settled
2806
+ settled[pname] = max(settled[pname], generation)
2807
+
2808
+ def _awaiting_ref(self_, pname: str) -> bool:
2809
+ """Whether an asynchronous reference has not yet produced a value."""
2810
+ if self_.self is None:
2811
+ return False
2812
+ private = self_.self._param__private
2813
+ return private.async_ref_scheduled[pname] != private.async_ref_settled[pname]
2814
+
2815
+ async def _async_ref(self_, pname: str, awaitable: t.Awaitable[t.Any], generation: int = 0):
2771
2816
  if self_.self is None:
2772
2817
  return
2773
2818
  if not self_.self._param__private.initialized:
2774
- async_executor(partial(self_._async_ref, pname, awaitable))
2819
+ async_executor(partial(self_._async_ref, pname, awaitable, generation))
2775
2820
  return
2776
2821
 
2777
2822
  import asyncio
2778
2823
  current_task = asyncio.current_task()
2779
2824
  running_task = self_.self._param__private.async_refs.get(pname)
2780
- if running_task is None:
2825
+ if running_task is not current_task:
2826
+ if running_task is not None:
2827
+ running_task.cancel()
2781
2828
  self_.self._param__private.async_refs[pname] = current_task
2782
- elif current_task is not running_task:
2783
- self_.self._param__private.async_refs[pname].cancel()
2784
2829
  try:
2785
2830
  if isinstance(awaitable, types.AsyncGeneratorType):
2786
2831
  async for new_obj in awaitable:
2787
2832
  with _syncing(self_.self, (pname,)):
2788
2833
  self_.update({pname: new_obj})
2834
+ self_._settle_async_ref(pname, generation)
2789
2835
  else:
2790
2836
  with _syncing(self_.self, (pname,)):
2791
2837
  try:
2792
2838
  self_.update({pname: await awaitable})
2793
2839
  except Skip:
2794
2840
  pass
2841
+ self_._settle_async_ref(pname, generation)
2795
2842
  finally:
2796
- # Ensure we clean up but only if the task matches the current task
2797
- if self_.self._param__private.async_refs.get(pname) is current_task:
2798
- del self_.self._param__private.async_refs[pname]
2843
+ self_._settle_async_ref(pname, generation)
2844
+ # Ensure we clean up but only if the task matches the current task,
2845
+ # i.e. only the resolution that still owns the reference clears it.
2846
+ async_refs = self_.self._param__private.async_refs
2847
+ if pname in async_refs and async_refs[pname] is current_task:
2848
+ del async_refs[pname]
2799
2849
 
2800
2850
  @classmethod
2801
2851
  def _changed(cls, event):
@@ -5638,6 +5688,8 @@ class _InstancePrivate:
5638
5688
  'dynamic_watchers',
5639
5689
  'params',
5640
5690
  'async_refs',
5691
+ 'async_ref_scheduled',
5692
+ 'async_ref_settled',
5641
5693
  'refs',
5642
5694
  'ref_watchers',
5643
5695
  'syncing',
@@ -5651,6 +5703,8 @@ class _InstancePrivate:
5651
5703
  dynamic_watchers: defaultdict[str, list[Watcher]]
5652
5704
  params: dict[str, Parameter]
5653
5705
  async_refs: dict[str, t.Any]
5706
+ async_ref_scheduled: defaultdict[str, int]
5707
+ async_ref_settled: defaultdict[str, int]
5654
5708
  refs: dict[str, t.Any]
5655
5709
  ref_watchers: list[tuple[tuple[str, ...], Watcher]]
5656
5710
  syncing: set[str]
@@ -5681,6 +5735,8 @@ class _InstancePrivate:
5681
5735
  }
5682
5736
  self.ref_watchers = []
5683
5737
  self.async_refs = {}
5738
+ self.async_ref_scheduled = defaultdict(int)
5739
+ self.async_ref_settled = defaultdict(int)
5684
5740
  self.parameters_state = parameters_state
5685
5741
  self.dynamic_watchers = defaultdict(list, dynamic_watchers or ())
5686
5742
  self.params = {} if params is None else params
@@ -115,6 +115,8 @@ from ._utils import _to_async_gen, iscoroutinefunction, full_groupby
115
115
  if t.TYPE_CHECKING:
116
116
  from typing_extensions import Self
117
117
 
118
+ from .parameterized import Watcher
119
+
118
120
  _P = t.ParamSpec('_P')
119
121
  _R = t.TypeVar('_R')
120
122
  _Y = t.TypeVar('_Y')
@@ -1374,10 +1376,13 @@ class _WeakInvalidator:
1374
1376
  ``rx._watch_invalidation``).
1375
1377
  """
1376
1378
 
1377
- __slots__ = ('_ref', '__weakref__')
1379
+ __slots__ = ('_ref', '_watcher', '__weakref__')
1380
+
1381
+ _watcher: Watcher | None
1378
1382
 
1379
1383
  def __init__(self, method):
1380
1384
  self._ref = weakref.WeakMethod(method)
1385
+ self._watcher = None
1381
1386
 
1382
1387
  def __call__(self, *events):
1383
1388
  method = self._ref()
@@ -1385,14 +1390,48 @@ class _WeakInvalidator:
1385
1390
  return method(*events)
1386
1391
 
1387
1392
 
1388
- def _remove_watcher(owner, watcher):
1389
- """Unwatch ``watcher`` from ``owner``, ignoring if it is already gone."""
1393
+ def _remove_watcher(
1394
+ owner_ref: weakref.ref[Parameterized | type[Parameterized]],
1395
+ invalidator_ref: weakref.ref[_WeakInvalidator],
1396
+ ) -> None:
1397
+ """
1398
+ Unwatch a dead node's invalidation watcher, ignoring if it is already gone.
1399
+
1400
+ Both refs must be weak: ``weakref.finalize`` holds its arguments until the
1401
+ referent dies, so a strong owner (or ``Watcher``, whose ``inst`` is the
1402
+ owner) would make the node uncollectable. ``Watcher`` subclasses ``tuple``
1403
+ and cannot be weakly referenced, so it is reached via the invalidator.
1404
+ """
1405
+ owner, invalidator = owner_ref(), invalidator_ref()
1406
+ if owner is None or invalidator is None or invalidator._watcher is None:
1407
+ return
1390
1408
  try:
1391
- owner.param.unwatch(watcher)
1409
+ owner.param.unwatch(invalidator._watcher)
1392
1410
  except Exception:
1393
1411
  pass
1394
1412
 
1395
1413
 
1414
+ async def _close_stale(obj):
1415
+ """
1416
+ Discard an awaitable or async generator whose result is no longer needed.
1417
+
1418
+ Closing a coroutine that was never awaited also suppresses the warning
1419
+ Python emits when it is garbage collected.
1420
+ """
1421
+ try:
1422
+ if inspect.isasyncgen(obj):
1423
+ await obj.aclose()
1424
+ elif inspect.iscoroutine(obj):
1425
+ obj.close()
1426
+ except (StopAsyncIteration, GeneratorExit):
1427
+ pass
1428
+ except Exception:
1429
+ logger.debug(
1430
+ "Ignoring close error for stale reactive task.",
1431
+ exc_info=True,
1432
+ )
1433
+
1434
+
1396
1435
  # When we only support python >= 3.11 we should exchange 'rx' with Self type annotation below.
1397
1436
  # See https://peps.python.org/pep-0673/
1398
1437
 
@@ -1558,6 +1597,8 @@ class rx:
1558
1597
  self._dirty_obj = False
1559
1598
  self._current_task = None
1560
1599
  self._resolve_generation = 0
1600
+ self._finished_generation = 0
1601
+ self._skipped = False
1561
1602
  self._error_state = None
1562
1603
  self._current_ = _current
1563
1604
  # _shared is used for branching rx pipelines where we clone the input.
@@ -1661,6 +1702,14 @@ class rx:
1661
1702
  inspect.isgeneratorfunction(fn)
1662
1703
  )
1663
1704
 
1705
+ @property
1706
+ def _awaiting(self) -> bool:
1707
+ """
1708
+ Whether an asynchronous resolution is in flight that has not yet
1709
+ produced a value for the current generation.
1710
+ """
1711
+ return self._resolve_generation != self._finished_generation
1712
+
1664
1713
  @property
1665
1714
  def _current(self):
1666
1715
  if self._error_state:
@@ -1758,9 +1807,13 @@ class rx:
1758
1807
  source does not pin the (potentially short-lived) derived node alive.
1759
1808
  A finalizer removes the watcher automatically once this node is garbage
1760
1809
  collected, keeping the source's watcher list from growing without bound.
1810
+ The finalizer is handed weak references only (see ``_remove_watcher``).
1761
1811
  """
1762
- watcher = owner.param._watch(_WeakInvalidator(method), names, precedence=-1)
1763
- weakref.finalize(self, _remove_watcher, owner, watcher)
1812
+ invalidator = _WeakInvalidator(method)
1813
+ invalidator._watcher = owner.param._watch(invalidator, names, precedence=-1)
1814
+ weakref.finalize(
1815
+ self, _remove_watcher, weakref.ref(owner), weakref.ref(invalidator)
1816
+ )
1764
1817
 
1765
1818
  def _invalidate_current(self, *events):
1766
1819
  if all(event.obj is self._trigger for event in events):
@@ -1772,14 +1825,23 @@ class rx:
1772
1825
  t.cast('t.Any', self._root)._dirty_obj = True
1773
1826
  self._error_state = None
1774
1827
 
1775
- async def _resolve_async(self, obj=None, generation=None):
1828
+ async def _resolve_async(self, obj=None, generation: int = 0):
1776
1829
  import asyncio
1777
- self._current_task = task = asyncio.current_task()
1778
- trigger = self._trigger
1779
1830
 
1780
1831
  def stale():
1781
1832
  return generation != self._resolve_generation
1782
1833
 
1834
+ if stale():
1835
+ # A newer resolution was requested before this task was scheduled,
1836
+ # so nothing has awaited obj yet and the operation has not begun.
1837
+ # Close it instead of computing a result that is already superseded.
1838
+ # This must happen before _current_task is claimed below, otherwise
1839
+ # the finally clause would clear the genuinely current task and hide
1840
+ # it from the next _lazy_resolve.
1841
+ await _close_stale(obj)
1842
+ return
1843
+ self._current_task = task = asyncio.current_task()
1844
+ trigger = self._trigger
1783
1845
  try:
1784
1846
  if trigger is None:
1785
1847
  return
@@ -1792,27 +1854,22 @@ class rx:
1792
1854
  if stale():
1793
1855
  return
1794
1856
  self._current_ = shared.rx.value
1857
+ self._finished_generation = generation
1795
1858
  trigger.param.trigger('value')
1796
1859
  elif inspect.isasyncgen(obj):
1797
1860
  async for val in obj:
1798
1861
  if stale():
1799
- try:
1800
- await obj.aclose()
1801
- except (StopAsyncIteration, GeneratorExit):
1802
- pass
1803
- except Exception:
1804
- logger.debug(
1805
- "Ignoring async generator close error for stale reactive task.",
1806
- exc_info=True,
1807
- )
1862
+ await _close_stale(obj)
1808
1863
  break
1809
1864
  self._current_ = val
1865
+ self._finished_generation = generation
1810
1866
  trigger.param.trigger('value')
1811
1867
  else:
1812
1868
  value = await obj
1813
1869
  if stale():
1814
1870
  return
1815
1871
  self._current_ = value
1872
+ self._finished_generation = generation
1816
1873
  trigger.param.trigger('value')
1817
1874
  except asyncio.CancelledError:
1818
1875
  return
@@ -1840,6 +1897,8 @@ class rx:
1840
1897
  if obj is Skip or obj is Undefined:
1841
1898
  self._current_ = Undefined
1842
1899
  raise Skip
1900
+ elif self._prev is not None and self._prev._skipped:
1901
+ raise Skip
1843
1902
  elif (
1844
1903
  self._shared is not None and
1845
1904
  self._method is None and
@@ -1851,9 +1910,14 @@ class rx:
1851
1910
  if self._is_async:
1852
1911
  self._shared.rx.value # trigger async resolve
1853
1912
  self._lazy_resolve()
1854
- else:
1855
- self._current_ = self._shared.rx.value
1856
- raise Skip
1913
+ raise Skip
1914
+ # Returns instead of raising Skip because this path does
1915
+ # resolve to a value, so it must mirror the shared node's
1916
+ # skip state rather than be marked skipped by the handler.
1917
+ self._current_ = self._shared.rx.value
1918
+ self._skipped = self._shared._skipped
1919
+ self._dirty = False
1920
+ return self._current_
1857
1921
  operation = self._operation
1858
1922
  if operation:
1859
1923
  obj = self._eval_operation(obj, operation)
@@ -1864,13 +1928,19 @@ class rx:
1864
1928
  raise Skip
1865
1929
  except Skip:
1866
1930
  self._dirty = False
1931
+ self._skipped = True
1867
1932
  return self._current_
1868
1933
  except Exception as e:
1869
1934
  self._error_state = e
1870
1935
  raise e
1871
1936
  self._current_ = current = obj
1937
+ self._skipped = False
1872
1938
  else:
1873
1939
  current = self._current_
1940
+ # A node awaiting an asynchronous result still holds the value it
1941
+ # computed from the previous inputs; report it as skipped so it is
1942
+ # not propagated as if it were current.
1943
+ self._skipped = self._awaiting
1874
1944
  self._dirty = False
1875
1945
  if self._method:
1876
1946
  # E.g. `pi = dfi.A` leads to `pi._method` equal to `'A'`.
@@ -2210,6 +2280,11 @@ class rx:
2210
2280
  def _rx_transform(obj):
2211
2281
  if not isinstance(obj, rx):
2212
2282
  return obj
2213
- return bind(lambda *_: obj.rx.value, *obj._params)
2283
+ def resolve(*_):
2284
+ value = obj.rx.value
2285
+ if obj._skipped or value is Skip or value is Undefined:
2286
+ raise Skip
2287
+ return value
2288
+ return bind(resolve, *obj._params)
2214
2289
 
2215
2290
  register_reference_transform(_rx_transform)
@@ -866,6 +866,209 @@ async def test_reactive_async_gen_pipe_with_dep():
866
866
  await async_wait_until(lambda: rxgen.rx.value == 10, interval=10)
867
867
  await async_wait_until(lambda: rxgen.rx.value == 11)
868
868
 
869
+ async def mul_slowly(value):
870
+ await asyncio.sleep(0.02)
871
+ return value*2
872
+
873
+ async def test_reactive_async_watcher_not_notified_while_awaiting():
874
+ irx = rx(1)
875
+ async_rx = irx.rx.pipe(mul_slowly)
876
+ items = []
877
+ async_rx.rx.watch(items.append)
878
+ assert async_rx.rx.value is param.Undefined
879
+ await async_wait_until(lambda: items == [2])
880
+ irx.rx.value = 2
881
+
882
+ # The awaited value has not resolved yet, so the watcher must not be
883
+ # notified with the value computed from the previous input.
884
+ assert items == [2]
885
+
886
+ await async_wait_until(lambda: items == [2, 4])
887
+
888
+ async def test_reactive_async_downstream_watcher_not_notified_while_awaiting():
889
+ irx = rx(1)
890
+ downstream = irx.rx.pipe(mul_slowly) + 10
891
+ items = []
892
+ downstream.rx.watch(items.append)
893
+ assert downstream.rx.value is param.Undefined
894
+ await async_wait_until(lambda: items == [12])
895
+ irx.rx.value = 2
896
+ assert items == [12]
897
+ await async_wait_until(lambda: items == [12, 14])
898
+
899
+ async def test_reactive_async_downstream_not_computed_while_awaiting():
900
+ computed = []
901
+ def add(value):
902
+ computed.append(value)
903
+ return value+10
904
+
905
+ irx = rx(1)
906
+ downstream = irx.rx.pipe(mul_slowly).rx.pipe(add)
907
+ downstream.rx.watch()
908
+ downstream.rx.value
909
+ await async_wait_until(lambda: computed == [2])
910
+ irx.rx.value = 2
911
+
912
+ # The downstream operation must not be applied to the superseded value.
913
+ assert computed == [2]
914
+
915
+ await async_wait_until(lambda: computed == [2, 4])
916
+
917
+ async def test_reactive_async_rapid_updates_notify_once():
918
+ irx = rx(1)
919
+ async_rx = irx.rx.pipe(mul_slowly)
920
+ items = []
921
+ async_rx.rx.watch(items.append)
922
+ async_rx.rx.value
923
+ await async_wait_until(lambda: items == [2])
924
+ for value in (2, 3, 4):
925
+ irx.rx.value = value
926
+ await async_wait_until(lambda: items == [2, 8])
927
+ assert items == [2, 8]
928
+
929
+ def test_reactive_skip_value_does_not_notify_watcher():
930
+ P = Parameters(integer=1)
931
+
932
+ def skip_values(v):
933
+ if v > 2:
934
+ raise Skip
935
+ return v+1
936
+
937
+ i = rx(P.param.integer).rx.pipe(skip_values)
938
+ items = []
939
+ i.rx.watch(items.append)
940
+ P.integer = 2
941
+ assert items == [3]
942
+
943
+ # The operation skipped, so the watcher must not be notified with the
944
+ # value computed from the previous input.
945
+ P.integer = 3
946
+ assert items == [3]
947
+ assert i.rx.value == 3
948
+
949
+ async def test_reactive_async_ref_not_synced_while_awaiting():
950
+ class Ref(param.Parameterized):
951
+ value = param.Integer(default=0, allow_refs=True)
952
+
953
+ irx = rx(1)
954
+ p = Ref(value=irx.rx.pipe(mul_slowly))
955
+ await async_wait_until(lambda: p.value == 2)
956
+ irx.rx.value = 2
957
+ assert p.value == 2
958
+ await async_wait_until(lambda: p.value == 4)
959
+
960
+ async def test_reactive_async_superseded_updates_not_computed():
961
+ started, finished = [], []
962
+
963
+ async def mul(value):
964
+ started.append(value)
965
+ await asyncio.sleep(0.02)
966
+ finished.append(value)
967
+ return value*2
968
+
969
+ irx = rx(1)
970
+ async_rx = irx.rx.pipe(mul)
971
+ items = []
972
+ async_rx.rx.watch(items.append)
973
+ async_rx.rx.value
974
+ await async_wait_until(lambda: items == [2])
975
+ assert started == [1]
976
+
977
+ # The updates arrive without yielding to the event loop, so the tasks they
978
+ # schedule have not started by the time the next one supersedes them.
979
+ for value in (2, 3, 4, 5):
980
+ irx.rx.value = value
981
+
982
+ await async_wait_until(lambda: items == [2, 10])
983
+
984
+ # Only the final update was computed; the superseded coroutines were closed
985
+ # before their bodies began.
986
+ assert started == [1, 5]
987
+ assert finished == [1, 5]
988
+
989
+ async def test_reactive_async_gen_superseded_updates_not_computed():
990
+ started = []
991
+
992
+ async def gen(value):
993
+ started.append(value)
994
+ yield value*2
995
+
996
+ irx = rx(1)
997
+ async_rx = irx.rx.pipe(gen)
998
+ async_rx.rx.watch()
999
+ async_rx.rx.value
1000
+ await async_wait_until(lambda: async_rx.rx.value == 2)
1001
+ assert started == [1]
1002
+
1003
+ for value in (2, 3, 4, 5):
1004
+ irx.rx.value = value
1005
+
1006
+ await async_wait_until(lambda: async_rx.rx.value == 10)
1007
+
1008
+ # A superseded async generator is closed before it is first iterated, so
1009
+ # its body never runs.
1010
+ assert started == [1, 5]
1011
+
1012
+ async def test_reactive_async_running_task_is_cancelled():
1013
+ cancelled = []
1014
+
1015
+ async def mul(value):
1016
+ try:
1017
+ await asyncio.sleep(0.1)
1018
+ except asyncio.CancelledError:
1019
+ cancelled.append(value)
1020
+ raise
1021
+ return value*2
1022
+
1023
+ irx = rx(1)
1024
+ async_rx = irx.rx.pipe(mul)
1025
+ async_rx.rx.watch()
1026
+ async_rx.rx.value
1027
+
1028
+ # Yield to the event loop so the body is actually suspended on its await;
1029
+ # a task in that state cannot be skipped, it has to be cancelled.
1030
+ await asyncio.sleep(0.01)
1031
+ irx.rx.value = 2
1032
+
1033
+ await async_wait_until(lambda: async_rx.rx.value == 4)
1034
+ assert cancelled == [1]
1035
+
1036
+ @pytest.mark.parametrize('lazy', [False, True])
1037
+ async def test_async_shared_rx_superseded_updates_computed_once(lazy):
1038
+ call_count = 0
1039
+
1040
+ class Model(param.Parameterized):
1041
+ a = param.Number(1.0)
1042
+
1043
+ model = Model()
1044
+
1045
+ async def expensive_compute(a):
1046
+ nonlocal call_count
1047
+ call_count += 1
1048
+ await asyncio.sleep(0.02)
1049
+ return {"x": a + 1, "y": a * 2}
1050
+
1051
+ shared = rx(model.param.a, lazy=lazy).rx.pipe(expensive_compute)
1052
+ x_rx = shared.rx.pipe(lambda d: d["x"])
1053
+ y_rx = shared.rx.pipe(lambda d: d["y"])
1054
+
1055
+ x_rx.rx.value
1056
+ y_rx.rx.value
1057
+ await async_wait_until(lambda: call_count == 1)
1058
+
1059
+ for value in (2.0, 3.0, 4.0):
1060
+ model.a = value
1061
+
1062
+ x_rx.rx.value
1063
+ y_rx.rx.value
1064
+ await async_wait_until(
1065
+ lambda: x_rx.rx.value == 5 and y_rx.rx.value == 8
1066
+ )
1067
+
1068
+ # The branches resolve through the shared node rather than recomputing, and
1069
+ # the superseded updates are not computed at all.
1070
+ assert call_count == 2
1071
+
869
1072
  @pytest.mark.parametrize('lazy', [False, True])
870
1073
  def test_root_invalidation(lazy):
871
1074
  arx = rx('a', lazy=lazy)
@@ -1056,3 +1259,54 @@ def test_reactive_derived_node_is_garbage_collected():
1056
1259
  a.rx.value = 5
1057
1260
  assert c.rx.value == 15
1058
1261
  assert watcher_count(a) > baseline
1262
+
1263
+
1264
+ def _rx_from_closure():
1265
+ """Build an object holding an rx pipeline whose root function closes over it."""
1266
+ class Owner:
1267
+ pass
1268
+
1269
+ owner = Owner()
1270
+
1271
+ def compute(x):
1272
+ return x + len(repr(owner)) * 0
1273
+
1274
+ owner.expr = param.rx(compute)(41)
1275
+ return owner
1276
+
1277
+
1278
+ def _rx_from_bound_method():
1279
+ """Build an object holding an rx pipeline rooted in one of its own methods."""
1280
+ class Owner:
1281
+ def __init__(self):
1282
+ self.expr = param.rx(self._compute)(41)
1283
+
1284
+ def _compute(self, x):
1285
+ return x
1286
+
1287
+ return Owner()
1288
+
1289
+
1290
+ @pytest.mark.parametrize('factory', [_rx_from_closure, _rx_from_bound_method])
1291
+ def test_reactive_function_rooted_node_does_not_pin_its_owner(factory):
1292
+ # weakref.finalize holds its arguments until the referent is collected, so
1293
+ # the invalidation cleanup must not own a path back to the node it cleans up.
1294
+ owner = factory()
1295
+ assert owner.expr.rx.value == 41
1296
+
1297
+ ref = weakref.ref(owner)
1298
+ del owner
1299
+ gc.collect()
1300
+ assert ref() is None
1301
+
1302
+
1303
+ @pytest.mark.parametrize('factory', [_rx_from_closure, _rx_from_bound_method])
1304
+ def test_reactive_function_rooted_nodes_do_not_accumulate(factory):
1305
+ refs = []
1306
+ for _ in range(50):
1307
+ owner = factory()
1308
+ owner.expr.rx.value
1309
+ refs.append(weakref.ref(owner))
1310
+ del owner
1311
+ gc.collect()
1312
+ assert all(ref() is None for ref in refs)
@@ -304,6 +304,55 @@ async def test_async_generator_ref_cancelled():
304
304
  assert task2 is async_task2
305
305
  assert p._param__private.async_refs['string'] is task2
306
306
 
307
+ async def test_async_ref_cancelled_on_dependency_change():
308
+ started, finished = [], []
309
+
310
+ class Source(param.Parameterized):
311
+ x = param.Number(default=0)
312
+
313
+ async def slow(i):
314
+ started.append(i)
315
+ await asyncio.sleep(0.1)
316
+ finished.append(i)
317
+ return str(i)
318
+
319
+ source = Source()
320
+ p = Parameters(string=bind(slow, source.param.x))
321
+ for i in (1, 2, 3):
322
+ source.x = i
323
+ await asyncio.sleep(0.01)
324
+
325
+ await wait_for_value(p, 'string', '3', timeout=1)
326
+ assert started == [0, 1, 2, 3]
327
+ assert finished == [3]
328
+
329
+ await asyncio.sleep(0.05)
330
+ assert 'string' not in p._param__private.async_refs
331
+
332
+ async def test_async_generator_ref_cancelled_on_dependency_change():
333
+ emitted = []
334
+
335
+ class Source(param.Parameterized):
336
+ x = param.Number(default=0)
337
+
338
+ async def gen(i):
339
+ while True:
340
+ emitted.append(i)
341
+ yield str(i)
342
+ await asyncio.sleep(0.01)
343
+
344
+ source = Source()
345
+ p = Parameters(string=bind(gen, source.param.x))
346
+ await asyncio.sleep(0.05)
347
+ source.x = 1
348
+ await asyncio.sleep(0.05)
349
+ source.x = 2
350
+ await wait_for_value(p, 'string', '2', timeout=0.5)
351
+
352
+ emitted.clear()
353
+ await asyncio.sleep(0.05)
354
+ assert set(emitted) == {2}
355
+
307
356
  async def test_generator_ref_cancelled():
308
357
  threads = []
309
358
  def gen_strings1():
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes