param 2.4.2rc0__tar.gz → 2.4.2rc2__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.2rc2}/PKG-INFO +1 -1
  2. {param-2.4.2rc0 → param-2.4.2rc2}/param/_utils.py +55 -4
  3. {param-2.4.2rc0 → param-2.4.2rc2}/param/_version.py +2 -2
  4. {param-2.4.2rc0 → param-2.4.2rc2}/param/parameterized.py +70 -14
  5. {param-2.4.2rc0 → param-2.4.2rc2}/param/reactive.py +124 -27
  6. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testreactive.py +455 -0
  7. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testrefs.py +49 -0
  8. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testutils.py +51 -0
  9. {param-2.4.2rc0 → param-2.4.2rc2}/.gitignore +0 -0
  10. {param-2.4.2rc0 → param-2.4.2rc2}/LICENSE.txt +0 -0
  11. {param-2.4.2rc0 → param-2.4.2rc2}/README.md +0 -0
  12. {param-2.4.2rc0 → param-2.4.2rc2}/numbergen/__init__.py +0 -0
  13. {param-2.4.2rc0 → param-2.4.2rc2}/param/__init__.py +0 -0
  14. {param-2.4.2rc0 → param-2.4.2rc2}/param/depends.py +0 -0
  15. {param-2.4.2rc0 → param-2.4.2rc2}/param/display.py +0 -0
  16. {param-2.4.2rc0 → param-2.4.2rc2}/param/ipython.py +0 -0
  17. {param-2.4.2rc0 → param-2.4.2rc2}/param/mypy_plugin.py +0 -0
  18. {param-2.4.2rc0 → param-2.4.2rc2}/param/parameters.py +0 -0
  19. {param-2.4.2rc0 → param-2.4.2rc2}/param/py.typed +0 -0
  20. {param-2.4.2rc0 → param-2.4.2rc2}/param/serializer.py +0 -0
  21. {param-2.4.2rc0 → param-2.4.2rc2}/param/version.py +0 -0
  22. {param-2.4.2rc0 → param-2.4.2rc2}/pyproject.toml +0 -0
  23. {param-2.4.2rc0 → param-2.4.2rc2}/tests/__init__.py +0 -0
  24. {param-2.4.2rc0 → param-2.4.2rc2}/tests/assert_types.py +0 -0
  25. {param-2.4.2rc0 → param-2.4.2rc2}/tests/conftest.py +0 -0
  26. {param-2.4.2rc0 → param-2.4.2rc2}/tests/pyrightconfig-bare.json +0 -0
  27. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testaddparameter.py +0 -0
  28. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testbind.py +0 -0
  29. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testbooleanparam.py +0 -0
  30. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testbytesparam.py +0 -0
  31. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcalendardateparam.py +0 -0
  32. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcalendardaterangeparam.py +0 -0
  33. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcallable.py +0 -0
  34. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testclassselector.py +0 -0
  35. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcolorparameter.py +0 -0
  36. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcomparator.py +0 -0
  37. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcompositeparams.py +0 -0
  38. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testcustomparam.py +0 -0
  39. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdateparam.py +0 -0
  40. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdaterangeparam.py +0 -0
  41. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdefaultfactory.py +0 -0
  42. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdefaults.py +0 -0
  43. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdeprecations.py +0 -0
  44. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testdynamicparams.py +0 -0
  45. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testfiledeserialization.py +0 -0
  46. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testfileselector.py +0 -0
  47. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testimports.py +0 -0
  48. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testipythonmagic.py +0 -0
  49. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testjsonserialization.py +0 -0
  50. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testlist.py +0 -0
  51. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testlistselector.py +0 -0
  52. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testmultifileselector.py +0 -0
  53. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testnumbergen.py +0 -0
  54. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testnumberparameter.py +0 -0
  55. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testnumpy.py +0 -0
  56. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testobjectselector.py +0 -0
  57. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testpandas.py +0 -0
  58. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparamdepends.py +0 -0
  59. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparameter.py +0 -0
  60. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparameterizedobject.py +0 -0
  61. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparameterizedrepr.py +0 -0
  62. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparamoutput.py +0 -0
  63. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testparamunion.py +0 -0
  64. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testpathparam.py +0 -0
  65. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testpickle.py +0 -0
  66. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testrangeparameter.py +0 -0
  67. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testreprhtml.py +0 -0
  68. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testselector.py +0 -0
  69. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testsignatures.py +0 -0
  70. {param-2.4.2rc0 → param-2.4.2rc2}/tests/teststringparam.py +0 -0
  71. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testtimedependent.py +0 -0
  72. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testtupleparam.py +0 -0
  73. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testversion.py +0 -0
  74. {param-2.4.2rc0 → param-2.4.2rc2}/tests/testwatch.py +0 -0
  75. {param-2.4.2rc0 → param-2.4.2rc2}/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.2rc2
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
@@ -12,7 +12,7 @@ import warnings
12
12
  from collections import OrderedDict, abc, defaultdict
13
13
  from contextlib import contextmanager
14
14
  from textwrap import dedent
15
- from threading import get_ident
15
+ from threading import get_ident, local
16
16
 
17
17
  if t.TYPE_CHECKING:
18
18
  import asyncio
@@ -608,18 +608,69 @@ def _in_ipython():
608
608
 
609
609
  _running_tasks: set[asyncio.Task] = set()
610
610
 
611
+ _thread_state = local()
612
+
613
+ def _fallback_event_loop() -> asyncio.AbstractEventLoop:
614
+ """
615
+ Return the event loop to drive coroutines on when nothing else is running.
616
+
617
+ The loop is cached per thread and reused, since creating one per call leaks
618
+ the file descriptors each loop holds. It is kept thread-local because
619
+ ``run_until_complete`` may not be driven from two threads at once.
620
+ """
621
+ import asyncio
622
+ event_loop = getattr(_thread_state, 'event_loop', None)
623
+ if event_loop is None or event_loop.is_closed():
624
+ event_loop = asyncio.new_event_loop()
625
+ _thread_state.event_loop = event_loop
626
+ return event_loop
627
+
628
+ def _drain_fallback_loop(event_loop: asyncio.AbstractEventLoop) -> None:
629
+ """
630
+ Finish off anything left running on the fallback loop.
631
+
632
+ A coroutine driven by :func:`async_executor` may schedule further work
633
+ before it completes, which ``run_until_complete`` leaves pending. Since the
634
+ loop is reused, such a leftover would otherwise resume in the middle of an
635
+ unrelated drive, so it is cancelled and given the chance to clean up here.
636
+ """
637
+ import asyncio
638
+ pending = [task for task in asyncio.all_tasks(event_loop) if not task.done()]
639
+ if not pending:
640
+ return
641
+ for task in pending:
642
+ task.cancel()
643
+ event_loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
644
+
611
645
  def async_executor(func):
646
+ """
647
+ Schedule the awaitable returned by ``func`` on the running event loop.
648
+
649
+ Without a running loop the awaitable is instead driven to completion on a
650
+ loop of param's own, i.e. the call blocks the caller until the coroutine
651
+ has finished. Applications that can offer a loop (such as Panel) are
652
+ expected to override ``param.parameterized.async_executor``.
653
+ """
612
654
  import asyncio
613
655
  try:
614
656
  event_loop = asyncio.get_running_loop()
615
657
  except RuntimeError:
616
- event_loop = asyncio.new_event_loop()
617
- if event_loop.is_running():
658
+ event_loop = None
659
+ if event_loop is not None:
618
660
  task = asyncio.ensure_future(func())
619
661
  _running_tasks.add(task)
620
662
  task.add_done_callback(_running_tasks.discard)
621
- else:
663
+ return
664
+ event_loop = _fallback_event_loop()
665
+ try:
622
666
  event_loop.run_until_complete(func())
667
+ except asyncio.CancelledError:
668
+ # A coroutine superseded while it was being driven synchronously must
669
+ # not surface the cancellation in the caller, which is generally an
670
+ # unrelated attribute access or parameter update.
671
+ pass
672
+ finally:
673
+ _drain_fallback_loop(event_loop)
623
674
 
624
675
  @t.runtime_checkable
625
676
  class _HasTypes(t.Protocol):
@@ -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.2rc2'
22
+ __version_tuple__ = version_tuple = (2, 4, 2, 'rc2')
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.
@@ -1574,7 +1615,8 @@ class rx:
1574
1615
  self._trigger: Trigger | None
1575
1616
  if operation and (iscoroutinefunction(operation['fn']) or inspect.isgeneratorfunction(operation['fn'])):
1576
1617
  self._trigger = Trigger(internal=True)
1577
- self._current_ = Undefined
1618
+ self._current_ = Undefined
1619
+ self._dirty = True # Otherwise current will be stuck as Undefined.
1578
1620
  else:
1579
1621
  self._trigger = None
1580
1622
  self._root = self._compute_root()
@@ -1661,6 +1703,14 @@ class rx:
1661
1703
  inspect.isgeneratorfunction(fn)
1662
1704
  )
1663
1705
 
1706
+ @property
1707
+ def _awaiting(self) -> bool:
1708
+ """
1709
+ Whether an asynchronous resolution is in flight that has not yet
1710
+ produced a value for the current generation.
1711
+ """
1712
+ return self._resolve_generation != self._finished_generation
1713
+
1664
1714
  @property
1665
1715
  def _current(self):
1666
1716
  if self._error_state:
@@ -1758,9 +1808,13 @@ class rx:
1758
1808
  source does not pin the (potentially short-lived) derived node alive.
1759
1809
  A finalizer removes the watcher automatically once this node is garbage
1760
1810
  collected, keeping the source's watcher list from growing without bound.
1811
+ The finalizer is handed weak references only (see ``_remove_watcher``).
1761
1812
  """
1762
- watcher = owner.param._watch(_WeakInvalidator(method), names, precedence=-1)
1763
- weakref.finalize(self, _remove_watcher, owner, watcher)
1813
+ invalidator = _WeakInvalidator(method)
1814
+ invalidator._watcher = owner.param._watch(invalidator, names, precedence=-1)
1815
+ weakref.finalize(
1816
+ self, _remove_watcher, weakref.ref(owner), weakref.ref(invalidator)
1817
+ )
1764
1818
 
1765
1819
  def _invalidate_current(self, *events):
1766
1820
  if all(event.obj is self._trigger for event in events):
@@ -1772,17 +1826,26 @@ class rx:
1772
1826
  t.cast('t.Any', self._root)._dirty_obj = True
1773
1827
  self._error_state = None
1774
1828
 
1775
- async def _resolve_async(self, obj=None, generation=None):
1829
+ async def _resolve_async(self, obj=None, generation: int = 0):
1776
1830
  import asyncio
1777
- self._current_task = task = asyncio.current_task()
1778
- trigger = self._trigger
1779
1831
 
1780
1832
  def stale():
1781
1833
  return generation != self._resolve_generation
1782
1834
 
1835
+ if stale():
1836
+ # A newer resolution was requested before this task was scheduled,
1837
+ # so nothing has awaited obj yet and the operation has not begun.
1838
+ # Close it instead of computing a result that is already superseded.
1839
+ # This must happen before _current_task is claimed below, otherwise
1840
+ # the finally clause would clear the genuinely current task and hide
1841
+ # it from the next _lazy_resolve.
1842
+ await _close_stale(obj)
1843
+ return
1844
+ trigger = self._trigger
1845
+ if trigger is None:
1846
+ return
1847
+ self._current_task = task = asyncio.current_task()
1783
1848
  try:
1784
- if trigger is None:
1785
- return
1786
1849
  if obj is None:
1787
1850
  shared = self._shared
1788
1851
  if shared is None:
@@ -1792,30 +1855,36 @@ class rx:
1792
1855
  if stale():
1793
1856
  return
1794
1857
  self._current_ = shared.rx.value
1858
+ self._finished_generation = generation
1795
1859
  trigger.param.trigger('value')
1796
1860
  elif inspect.isasyncgen(obj):
1797
1861
  async for val in obj:
1798
1862
  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
- )
1863
+ await _close_stale(obj)
1808
1864
  break
1809
1865
  self._current_ = val
1866
+ self._finished_generation = generation
1810
1867
  trigger.param.trigger('value')
1811
1868
  else:
1812
1869
  value = await obj
1813
1870
  if stale():
1814
1871
  return
1815
1872
  self._current_ = value
1873
+ self._finished_generation = generation
1816
1874
  trigger.param.trigger('value')
1817
1875
  except asyncio.CancelledError:
1818
1876
  return
1877
+ except Exception as e:
1878
+ if stale():
1879
+ return
1880
+ self._finished_generation = generation
1881
+ if self._dirty or self._root._dirty_obj:
1882
+ # Ignoring as the inputs were invalidated while the async operation was running
1883
+ return
1884
+ # Mirror the synchronous path in _resolve.
1885
+ # For an async generator an raised exception ends the stream.
1886
+ self._error_state = e
1887
+ trigger.param.trigger('value')
1819
1888
  finally:
1820
1889
  if self._current_task is task:
1821
1890
  self._current_task = None
@@ -1840,6 +1909,8 @@ class rx:
1840
1909
  if obj is Skip or obj is Undefined:
1841
1910
  self._current_ = Undefined
1842
1911
  raise Skip
1912
+ elif self._prev is not None and self._prev._skipped:
1913
+ raise Skip
1843
1914
  elif (
1844
1915
  self._shared is not None and
1845
1916
  self._method is None and
@@ -1848,12 +1919,27 @@ class rx:
1848
1919
  # If this rx is cloned from an shared input then we make use
1849
1920
  # of the shared.rx.value to ensure branching pipelines do
1850
1921
  # not have to recompute the inputs multiple times.
1851
- if self._is_async:
1852
- self._shared.rx.value # trigger async resolve
1922
+ shared = self._shared
1923
+ value = shared.rx.value # triggers async resolve
1924
+ if self._is_async and (
1925
+ shared._awaiting or shared._current_task is not None
1926
+ ):
1927
+ # The shared node is still processing, resolve when finished
1853
1928
  self._lazy_resolve()
1854
- else:
1855
- self._current_ = self._shared.rx.value
1856
- raise Skip
1929
+ raise Skip
1930
+ # Returns instead of raising Skip because this path does
1931
+ # resolve to a value, so it must mirror the shared node's
1932
+ # skip state rather than be marked skipped by the handler.
1933
+ self._current_ = value
1934
+ self._skipped = shared._skipped
1935
+ if self._is_async:
1936
+ # The value was adopted without scheduling a task, so
1937
+ # claim a generation for it. This supersedes a task an
1938
+ # earlier operation may have scheduled and still awaits a resolution.
1939
+ self._resolve_generation += 1
1940
+ self._finished_generation = self._resolve_generation
1941
+ self._dirty = False
1942
+ return self._current_
1857
1943
  operation = self._operation
1858
1944
  if operation:
1859
1945
  obj = self._eval_operation(obj, operation)
@@ -1864,13 +1950,19 @@ class rx:
1864
1950
  raise Skip
1865
1951
  except Skip:
1866
1952
  self._dirty = False
1953
+ self._skipped = True
1867
1954
  return self._current_
1868
1955
  except Exception as e:
1869
1956
  self._error_state = e
1870
1957
  raise e
1871
1958
  self._current_ = current = obj
1959
+ self._skipped = False
1872
1960
  else:
1873
1961
  current = self._current_
1962
+ # A node awaiting an asynchronous result still holds the value it
1963
+ # computed from the previous inputs; report it as skipped so it is
1964
+ # not propagated as if it were current.
1965
+ self._skipped = self._awaiting
1874
1966
  self._dirty = False
1875
1967
  if self._method:
1876
1968
  # E.g. `pi = dfi.A` leads to `pi._method` equal to `'A'`.
@@ -2210,6 +2302,11 @@ class rx:
2210
2302
  def _rx_transform(obj):
2211
2303
  if not isinstance(obj, rx):
2212
2304
  return obj
2213
- return bind(lambda *_: obj.rx.value, *obj._params)
2305
+ def resolve(*_):
2306
+ value = obj.rx.value
2307
+ if obj._skipped or value is Skip or value is Undefined:
2308
+ raise Skip
2309
+ return value
2310
+ return bind(resolve, *obj._params)
2214
2311
 
2215
2312
  register_reference_transform(_rx_transform)