From 2170827e07ef61356b92ee5506452677d31cff86 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 8 Jun 2025 16:12:53 +0300 Subject: [PATCH] Value.get: Accept "default" parameter The idea is similar to e.g. Python's dict.get() method, which can take an optional default if a given key doesn't exist in the dict. This change would allow to users to "bootstrap" otherwise circular dependencies in simple cases. For example, it allows to turn this code: ``` from shiny.express import input, render, ui @render.express def myrender(): ui.input_select("sel", None, ["All", "So", "Much"], selected="All") input.sel() ``` which doesn't render anything nor produces errors (underneath it throws SilentException which isn't reported) into following code: ``` from shiny.express import input, render, ui @render.express def myrender(): ui.input_select("sel", None, ["All", "So", "Much"], selected=input.sel.get("All")) input.sel.get("All") ``` which works as expected (initial selected value is "All", and if user chooses another, it's preserved across myrender() run). --- shiny/reactive/_reactives.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/shiny/reactive/_reactives.py b/shiny/reactive/_reactives.py index c509d0809..0583b6d13 100644 --- a/shiny/reactive/_reactives.py +++ b/shiny/reactive/_reactives.py @@ -126,9 +126,15 @@ def __init__( def __call__(self) -> T: return self.get() - def get(self) -> T: + def get(self, default: T | MISSING_TYPE = MISSING) -> T: """ - Read the reactive value. + Read the reactive value. If value is not set, a default can be optionally + returned. + + Parameters + ---------- + default + An optional default to return if value is not set. Returns ------- @@ -138,7 +144,7 @@ def get(self) -> T: Raises ------ :class:`~shiny.types.SilentException` - If the value is not set. + If the value is not set and default is not provided. RuntimeError If called from outside a reactive function. """ @@ -146,6 +152,8 @@ def get(self) -> T: self._value_dependents.register() if isinstance(self._value, MISSING_TYPE): + if default is not MISSING: + return default raise SilentException return self._value