-
-
Notifications
You must be signed in to change notification settings - Fork 80
Add LiteralRef wrapper to assign ref-like values without resolving #1091
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
philippjfr
wants to merge
5
commits into
main
Choose a base branch
from
raw_wrapper
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
730e37f
Add raw wrapper to assign ref-like values without resolving
philippjfr c27db88
Apply suggestions from code review
philippjfr 1cc60eb
Fix test
philippjfr b74271b
Rename to LiteralRef and add docs and tests
philippjfr 741f970
Remove stray print
philippjfr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -265,6 +265,92 @@ | |||||
| ":::" | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "ae3232e6-91dd-4a09-8301-b5a79ae42f8f", | ||||||
| "metadata": {}, | ||||||
| "source": [ | ||||||
| "## Assigning refs literally with `LiteralRef`\n", | ||||||
| "\n", | ||||||
| "Sometimes you don’t want Param to resolve a ref-like value on assignment—you want to store the ref object itself.\n", | ||||||
| "\n", | ||||||
| "Use `LiteralRef` to assign a ref as-is (verbatim), so you can forward it, serialize it, or resolve it later under different conditions." | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "15985908-d821-41a6-a4e0-41a8a49d9aae", | ||||||
| "metadata": {}, | ||||||
| "source": [ | ||||||
| "\n", | ||||||
| "By default, assigning a ref-like value resolves and links it:" | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "code", | ||||||
| "execution_count": null, | ||||||
| "id": "b2c80606-f60f-4534-b2da-608efd2c9ab8", | ||||||
| "metadata": {}, | ||||||
| "outputs": [], | ||||||
| "source": [ | ||||||
| "class Example(param.Parameterized):\n", | ||||||
| " value = param.Parameter(allow_refs=True)\n", | ||||||
| "\n", | ||||||
| "src = Example(value=\"A\")\n", | ||||||
| "dst = Example()\n", | ||||||
| "\n", | ||||||
| "dst.value = src.param.value\n", | ||||||
| "assert dst.value == \"A\"\n", | ||||||
| "src.value = \"B\"\n", | ||||||
| "assert dst.value == \"B\" # still linked" | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "3942b3d3-3d0f-4f99-bb9e-b79ee991b635", | ||||||
| "metadata": {}, | ||||||
| "source": [ | ||||||
| "i.e. the `dst.value` tracks the `src.value`. Wrapping the reference in the `LiteralRef` skips the resolution:" | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "code", | ||||||
| "execution_count": null, | ||||||
| "id": "cf3fae7b-7dc6-47b5-9ed9-78cd5799ff52", | ||||||
| "metadata": {}, | ||||||
| "outputs": [], | ||||||
| "source": [ | ||||||
| "dst.value = param.parameterized.LiteralRef(src.param.value)\n", | ||||||
| "\n", | ||||||
| "dst.value" | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "e7174aad-4751-436e-8b68-36557597fccc", | ||||||
| "metadata": {}, | ||||||
| "source": [ | ||||||
| "i.e. Param unwraps the `LiteralRef` object but does not resolve the `Parameter` reference. `dst` now holds the actual `Parameter` object." | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "481223e8-750e-41b4-8376-63381b2012c6", | ||||||
| "metadata": {}, | ||||||
| "source": [ | ||||||
| "#### Key points\n", | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| "\n", | ||||||
| "- The wrapper is transient: it's unwrapped at assignment time; the stored value is the inner ref object.\n", | ||||||
| "- No subscription, no evaluation, no resolution occurs during assignment.\n", | ||||||
| "\n", | ||||||
| "#### When to use LiteralRef\n", | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| "\n", | ||||||
| "- You're wiring a graph of components and need to pass a ref downstream without linking it yet.\n", | ||||||
| "- You're building a config/serialization format that stores refs (not their current values).\n", | ||||||
| "- You have reactive/async producers you don't want to start/subscribe/consume during assignment.\n", | ||||||
| "- You want to preserve intent (“this is a ref”) instead of collapsing it to a concrete value." | ||||||
| ] | ||||||
| }, | ||||||
| { | ||||||
| "cell_type": "markdown", | ||||||
| "id": "6ffd34f8-211c-4945-95b8-e87ec712e028", | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -162,6 +162,36 @@ def get_logger(name: Optional[str] = None)->"logging.Logger": | |||||||||
| # Hook to apply to depends and bind arguments to turn them into valid parameters | ||||||||||
| _reference_transforms = [] | ||||||||||
|
|
||||||||||
| class LiteralRef: | ||||||||||
| """ | ||||||||||
| Wrapper type used to assign ref-like objects to Parameters *without* | ||||||||||
| triggering automatic resolution. | ||||||||||
|
|
||||||||||
| Normally, when a ref-like value (e.g. a Parameter, reactive expression, | ||||||||||
| async generator, etc.) is assigned to a Parameter attribute, Param | ||||||||||
| resolves it to its underlying value. Wrapping the object in ``LiteralRef`` | ||||||||||
| signals that the value should instead be stored as-is. | ||||||||||
|
|
||||||||||
| Example | ||||||||||
| ------- | ||||||||||
|
Comment on lines
+175
to
+176
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| >>> obj.some_param = param.LiteralRef(other.param.value) | ||||||||||
| >>> assert obj.some_param is other.param.value | ||||||||||
|
|
||||||||||
| Notes | ||||||||||
| ----- | ||||||||||
| - ``LiteralRef`` is only meaningful at assignment time; the wrapper is | ||||||||||
| unwrapped and not stored. | ||||||||||
| - The stored value is the inner object itself, not the ``LiteralRef`` instance. | ||||||||||
| - This allows safe serialization, forwarding, or deferred resolution of | ||||||||||
| ref-like values. | ||||||||||
| """ | ||||||||||
|
|
||||||||||
| __slots__ = ["value"] | ||||||||||
|
|
||||||||||
| def __init__(self, value): self.value = value | ||||||||||
| def __repr__(self): return f"LiteralRef({self.value!r})" | ||||||||||
|
|
||||||||||
|
|
||||||||||
| def register_reference_transform(transform): | ||||||||||
| """ | ||||||||||
| Append a transform to extract potential parameter dependencies | ||||||||||
|
|
@@ -170,7 +200,6 @@ def register_reference_transform(transform): | |||||||||
| Parameters | ||||||||||
| ---------- | ||||||||||
| transform: Callable[Any, Any] | ||||||||||
|
|
||||||||||
| """ | ||||||||||
| return _reference_transforms.append(transform) | ||||||||||
|
|
||||||||||
|
|
@@ -182,6 +211,8 @@ def transform_reference(arg): | |||||||||
| that are not simple Parameters or functions with dependency | ||||||||||
| definitions. | ||||||||||
| """ | ||||||||||
| if isinstance(arg, LiteralRef): | ||||||||||
| return arg.value | ||||||||||
| for transform in _reference_transforms: | ||||||||||
| if isinstance(arg, Parameter) or hasattr(arg, '_dinfo'): | ||||||||||
| break | ||||||||||
|
|
@@ -207,7 +238,9 @@ def eval_function_with_deps(function): | |||||||||
|
|
||||||||||
| def resolve_value(value, recursive=True): | ||||||||||
| """Resolve the current value of a dynamic reference.""" | ||||||||||
| if not recursive: | ||||||||||
| if isinstance(value, LiteralRef): | ||||||||||
| return value.value | ||||||||||
| elif not recursive: | ||||||||||
| pass | ||||||||||
| elif isinstance(value, (list, tuple)): | ||||||||||
| return type(value)(resolve_value(v) for v in value) | ||||||||||
|
|
@@ -231,7 +264,9 @@ def resolve_value(value, recursive=True): | |||||||||
|
|
||||||||||
| def resolve_ref(reference, recursive=False): | ||||||||||
| """Resolve all parameters a dynamic reference depends on.""" | ||||||||||
| if recursive: | ||||||||||
| if isinstance(reference, LiteralRef): | ||||||||||
| return [] | ||||||||||
| elif recursive: | ||||||||||
| if isinstance(reference, (list, tuple, set)): | ||||||||||
| return [r for v in reference for r in resolve_ref(v, recursive)] | ||||||||||
| elif isinstance(reference, dict): | ||||||||||
|
|
@@ -2442,10 +2477,12 @@ def _sync_refs(self_, *events): | |||||||||
| self_.update(updates) | ||||||||||
|
|
||||||||||
| def _resolve_ref(self_, pobj, value): | ||||||||||
| if isinstance(value, LiteralRef): | ||||||||||
| return None, None, value.value, False | ||||||||||
| is_gen = inspect.isgeneratorfunction(value) | ||||||||||
| is_async = iscoroutinefunction(value) or is_gen | ||||||||||
| deps = resolve_ref(value, recursive=pobj.nested_refs) | ||||||||||
| if not (deps or is_async or is_gen): | ||||||||||
| if not (deps or is_async or is_gen or pobj.nested_refs): | ||||||||||
| return None, None, value, False | ||||||||||
| ref = value | ||||||||||
| try: | ||||||||||
|
|
||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just to avoid the possible confusion that this would only work with the base
Parameter.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well this will error, because the ref value (i.e. the Parameter instance) is not a string.