pyglove 0.4.5.dev202501150808__py3-none-any.whl → 0.4.5.dev202501160808__py3-none-any.whl

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.
pyglove/core/__init__.py CHANGED
@@ -125,6 +125,9 @@ compound_class = symbolic.compound_class
125
125
  # Method for declaring a boilerplated class from a symbolic instance.
126
126
  boilerplate_class = symbolic.boilerplate_class
127
127
 
128
+ # Methods for contextual objects.
129
+ ContextualObject = symbolic.ContextualObject
130
+ contextual_attribute = symbolic.contextual_attribute
128
131
 
129
132
  #
130
133
  # Context manager for swapping wrapped class with their wrappers.
@@ -302,6 +305,10 @@ docstr = utils.docstr
302
305
  catch_errors = utils.catch_errors
303
306
  timeit = utils.timeit
304
307
 
308
+ contextual_override = utils.contextual_override
309
+ with_contextual_override = utils.with_contextual_override
310
+ contextual_value = utils.contextual_value
311
+
305
312
  colored = utils.colored
306
313
  decolor = utils.decolor
307
314
 
@@ -86,6 +86,10 @@ from pyglove.core.symbolic.compounding import compound
86
86
  from pyglove.core.symbolic.compounding import compound_class
87
87
  from pyglove.core.symbolic.boilerplate import boilerplate_class
88
88
 
89
+ from pyglove.core.symbolic.contextual_object import ContextualObject
90
+ from pyglove.core.symbolic.contextual_object import ContextualAttribute
91
+ from pyglove.core.symbolic.contextual_object import contextual_attribute
92
+
89
93
  # Inferential types.
90
94
  from pyglove.core.symbolic.base import Inferential
91
95
 
@@ -0,0 +1,288 @@
1
+ # Copyright 2025 The PyGlove Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contextual objects.
15
+
16
+ This module provides support for defining and working with `ContextualObject`s,
17
+ whose attributes can dynamically adapt based on context managers and parent
18
+ objects.
19
+
20
+ # Overview:
21
+
22
+ Contextual objects are specialized objects whose attribute values can be:
23
+ 1. Dynamically overridden using the `pg.contextual_override` context manager.
24
+ 2. Accessed via parent objects using the `pg.contextual_attribute` placeholder.
25
+
26
+ This flexibility is particularly useful in scenarios where attributes need
27
+ to respond to dynamic runtime conditions or inherit behavior from hierarchical
28
+ structures.
29
+
30
+ Example:
31
+
32
+ ```python
33
+ class A(pg.ContextualObject):
34
+ x: int
35
+ y: Any = pg.contextual_attribute()
36
+
37
+ a = A(1)
38
+ print(a.x) # 1
39
+ with pg.contextual_override(x=2):
40
+ print(a.x) # 2
41
+ print(a.x) #1
42
+
43
+ pg.Dict(y=3, a=a)
44
+ print(a.y) # 3. (Accessing parent's y)
45
+ ```
46
+ """
47
+
48
+ import threading
49
+ from typing import Annotated, Any, ContextManager, Dict, Optional, Type
50
+ from pyglove.core import utils as pg_utils
51
+ from pyglove.core.symbolic import base
52
+ from pyglove.core.symbolic import inferred as pg_inferred
53
+ from pyglove.core.symbolic import object as pg_object
54
+ from pyglove.core.views.html import tree_view
55
+
56
+
57
+ class ContextualObject(pg_object.Object):
58
+ """Base class for contextual objects.
59
+
60
+ Contextual objects are objects whose attributes can be dynamically overridden
61
+ using `pg.contextual_override` or resolved through
62
+ `pg.contextual_attribute`, allowing them to inherit values from their
63
+ containing objects.
64
+
65
+ Usages:
66
+
67
+ ```
68
+ # Define a contextual object.
69
+ class A(pg.ContextualObject):
70
+ x: int
71
+ y: Any = pg.contextual_attribute()
72
+
73
+ # Create an instance of A
74
+ a = A(1)
75
+ print(a.x) # Outputs: 1
76
+ print(a.y) # Raises an error, as `a` has no containing object.
77
+
78
+ # Define another contextual object containing an instance of A
79
+ class B(pg.ContextualObject):
80
+ y: int
81
+ a: A
82
+
83
+ # Create an instance of B, containing "a"
84
+ b = B(y=2, a=a)
85
+ print(a.y) # Outputs: 2, as "y" is resolved from the containing object (B).
86
+
87
+ # Contextual overrides are thread-specific
88
+ with pg.contextual_override(x=2):
89
+ print(a.x) # Outputs: 2
90
+
91
+ # Thread-specific behavior of `pg.contextual_override`
92
+ def foo(a):
93
+ print(a.x)
94
+
95
+ with pg.contextual_override(x=3):
96
+ t = threading.Thread(target=foo, args=(a,))
97
+ t.start()
98
+ t.join()
99
+ # Outputs: 1, because `pg.contextual_override` is limited to the current
100
+ # thread to avoid clashes in multi-threaded environments.
101
+
102
+ # To propagate the override to a new thread, use `pg.with_contextual_override`
103
+ with pg.contextual_override(x=3):
104
+ t = threading.Thread(target=pg.with_contextual_override(foo), args=(a,))
105
+ t.start()
106
+ t.join()
107
+ # Outputs: 3, as the override is explicitly propagated.
108
+ ```
109
+ """
110
+
111
+ # Override __repr__ format to use inferred values when available.
112
+ __repr_format_kwargs__ = dict(
113
+ compact=True,
114
+ use_inferred=True,
115
+ )
116
+
117
+ # Override __str__ format to use inferred values when available.
118
+ __str_format_kwargs__ = dict(
119
+ compact=False,
120
+ verbose=False,
121
+ use_inferred=True,
122
+ )
123
+
124
+ def _on_bound(self):
125
+ super()._on_bound()
126
+ self._contextual_overrides = threading.local()
127
+
128
+ def _sym_inferred(self, key: str, **kwargs):
129
+ """Override to allow attribute to access scoped value.
130
+
131
+ Args:
132
+ key: attribute name.
133
+ **kwargs: Optional keyword arguments for value inference.
134
+
135
+ Returns:
136
+ The value of the symbolic attribute. If not available, returns the
137
+ default value.
138
+
139
+ Raises:
140
+ AttributeError: If the attribute does not exist or contextual attribute
141
+ is not ready.
142
+ """
143
+ if key not in self._sym_attributes:
144
+ raise AttributeError(key)
145
+
146
+ # Step 1: Try use value from `self.override`.
147
+ # The reason is that `self.override` is short-lived and explicitly specified
148
+ # by the user in scenarios like `LangFunc.render`, which should not be
149
+ # affected by `pg.contextual_override`.
150
+ v = pg_utils.contextual.get_scoped_value(self._contextual_overrides, key)
151
+ if v is not None:
152
+ return v.value
153
+
154
+ # Step 2: Try use value from `pg.contextual_override` with `override_attrs`.
155
+ # This gives users a chance to override the bound attributes of components
156
+ # from the top, allowing change of bindings without modifying the code
157
+ # that produces the components.
158
+ override = pg_utils.contextual.get_contextual_override(key)
159
+ if override and override.override_attrs:
160
+ return override.value
161
+
162
+ # Step 3: Try use value from the symbolic tree, starting from self to
163
+ # the root of the tree.
164
+ # Step 4: If the value is not present, use the value from `context()` (
165
+ # override_attrs=False).
166
+ # Step 5: Otherwise use the default value from `ContextualAttribute`.
167
+ return super()._sym_inferred(key, context_override=override, **kwargs)
168
+
169
+ def override(
170
+ self,
171
+ **kwargs
172
+ ) -> ContextManager[Dict[str, pg_utils.contextual.ContextualOverride]]:
173
+ """Context manager to override the attributes of this component."""
174
+ vs = {
175
+ k: pg_utils.contextual.ContextualOverride(v)
176
+ for k, v in kwargs.items()
177
+ }
178
+ return pg_utils.contextual.contextual_scope(
179
+ self._contextual_overrides, **vs
180
+ )
181
+
182
+ def __getattribute__(self, name: str) -> Any:
183
+ """Override __getattribute__ to deal with class attribute override."""
184
+ if not name.startswith('_') and hasattr(self.__class__, name):
185
+ tls = self.__dict__.get('_contextual_overrides', None)
186
+ if tls is not None:
187
+ v = pg_utils.contextual.get_scoped_value(tls, name)
188
+ if v is not None:
189
+ return v.value
190
+ return super().__getattribute__(name)
191
+
192
+
193
+ class ContextualAttribute(
194
+ pg_inferred.ValueFromParentChain, tree_view.HtmlTreeView.Extension
195
+ ):
196
+ """Attributes whose values are inferred from the containing objects."""
197
+
198
+ NO_DEFAULT = (pg_utils.MISSING_VALUE,)
199
+
200
+ type: Annotated[Optional[Type[Any]], 'An optional type constraint.'] = None
201
+
202
+ default: Any = NO_DEFAULT
203
+
204
+ def value_from(
205
+ self,
206
+ parent,
207
+ *,
208
+ context_override: Optional[pg_utils.contextual.ContextualOverride] = None,
209
+ **kwargs,
210
+ ):
211
+ if (parent not in (None, self.sym_parent)
212
+ and isinstance(parent, ContextualObject)):
213
+ # Apply original search logic along the contextual object containing
214
+ # chain.
215
+ return super().value_from(parent, **kwargs)
216
+ elif parent is None:
217
+ # When there is no value inferred from the symbolic tree.
218
+ # Search context override, and then attribute-level default.
219
+ if context_override:
220
+ return context_override.value
221
+ if self.default == ContextualAttribute.NO_DEFAULT:
222
+ return pg_utils.MISSING_VALUE
223
+ return self.default
224
+ else:
225
+ return pg_utils.MISSING_VALUE
226
+
227
+ def _html_tree_view_content(
228
+ self,
229
+ *,
230
+ view: tree_view.HtmlTreeView,
231
+ parent: Any = None,
232
+ root_path: Optional[pg_utils.KeyPath] = None,
233
+ **kwargs,
234
+ ) -> tree_view.Html:
235
+ inferred_value = pg_utils.MISSING_VALUE
236
+ if isinstance(parent, base.Symbolic) and root_path:
237
+ inferred_value = parent.sym_inferred(
238
+ root_path.key, pg_utils.MISSING_VALUE
239
+ )
240
+
241
+ if inferred_value is not pg_utils.MISSING_VALUE:
242
+ kwargs.pop('name', None)
243
+ return view.render(
244
+ inferred_value, parent=self,
245
+ root_path=pg_utils.KeyPath('<inferred>', root_path),
246
+ **view.get_passthrough_kwargs(**kwargs)
247
+ )
248
+ return tree_view.Html.element(
249
+ 'div',
250
+ [
251
+ '(not available)',
252
+ ],
253
+ css_classes=['unavailable-contextual'],
254
+ )
255
+
256
+ def _html_tree_view_config(self) -> Dict[str, Any]:
257
+ return tree_view.HtmlTreeView.get_kwargs(
258
+ super()._html_tree_view_config(),
259
+ dict(
260
+ collapse_level=1,
261
+ )
262
+ )
263
+
264
+ @classmethod
265
+ def _html_tree_view_css_styles(cls) -> list[str]:
266
+ return super()._html_tree_view_css_styles() + [
267
+ """
268
+ .contextual-attribute {
269
+ color: purple;
270
+ }
271
+ .unavailable-contextual {
272
+ color: gray;
273
+ font-style: italic;
274
+ }
275
+ """
276
+ ]
277
+
278
+
279
+ # NOTE(daiyip): Returning Any instead of `pg.ContextualAttribute` to
280
+ # avoid pytype check error as `contextual_attribute()` can be assigned to any
281
+ # type.
282
+ def contextual_attribute(
283
+ type: Optional[Type[Any]] = None, # pylint: disable=redefined-builtin
284
+ default: Any = ContextualAttribute.NO_DEFAULT,
285
+ ) -> Any:
286
+ """Value marker for a contextual attribute."""
287
+ return ContextualAttribute(type=type, default=default, allow_partial=True)
288
+
@@ -0,0 +1,327 @@
1
+ # Copyright 2025 The PyGlove Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ from typing import Any
16
+ import unittest
17
+ import weakref
18
+
19
+ from pyglove.core import utils as pg_utils
20
+ from pyglove.core.symbolic import contextual_object
21
+
22
+ contextual_override = pg_utils.contextual_override
23
+ ContextualOverride = pg_utils.ContextualOverride
24
+ get_contextual_override = pg_utils.get_contextual_override
25
+ contextual_value = pg_utils.contextual_value
26
+ all_contextual_values = pg_utils.all_contextual_values
27
+
28
+ ContextualObject = contextual_object.ContextualObject
29
+ contextual_attribute = contextual_object.contextual_attribute
30
+
31
+
32
+ class ContextualObjectTest(unittest.TestCase):
33
+ """Tests for ContextualObject."""
34
+
35
+ def test_override(self):
36
+ class A(ContextualObject):
37
+ x: int
38
+
39
+ a = A(x=1)
40
+ with a.override(x=2, y=1):
41
+ self.assertEqual(a.x, 2)
42
+
43
+ # `y`` is not an attribute of `A`.
44
+ with self.assertRaises(AttributeError):
45
+ _ = a.y
46
+
47
+ def test_context(self):
48
+ class A(ContextualObject):
49
+ x: int
50
+ y: int = contextual_attribute()
51
+ z: int = contextual_attribute(default=-1)
52
+
53
+ with self.assertRaisesRegex(TypeError, '.* missing 1 required argument'):
54
+ _ = A()
55
+
56
+ a = A(x=1)
57
+ with self.assertRaisesRegex(
58
+ AttributeError, 'p'
59
+ ):
60
+ _ = a.p
61
+
62
+ with self.assertRaisesRegex(
63
+ AttributeError, '.* is not found under its context'
64
+ ):
65
+ _ = a.y
66
+
67
+ with contextual_override(y=1):
68
+ self.assertEqual(a.y, 1)
69
+
70
+ with self.assertRaisesRegex(
71
+ AttributeError, '.* is not found under its context'
72
+ ):
73
+ _ = a.y
74
+
75
+ # Use contextual default if it's not provided.
76
+ self.assertEqual(a.z, -1)
77
+
78
+ a1 = A(x=1, y=2)
79
+ self.assertEqual(a1.x, 1)
80
+ self.assertEqual(a1.y, 2)
81
+ self.assertEqual(a1.z, -1)
82
+
83
+ with contextual_override(x=3, y=3, z=3) as parent_override:
84
+ self.assertEqual(
85
+ parent_override,
86
+ dict(
87
+ x=ContextualOverride(3, cascade=False, override_attrs=False),
88
+ y=ContextualOverride(3, cascade=False, override_attrs=False),
89
+ z=ContextualOverride(3, cascade=False, override_attrs=False),
90
+ ),
91
+ )
92
+ self.assertEqual(
93
+ get_contextual_override('y'),
94
+ ContextualOverride(3, cascade=False, override_attrs=False),
95
+ )
96
+ self.assertEqual(contextual_value('x'), 3)
97
+ self.assertIsNone(contextual_value('f', None))
98
+ with self.assertRaisesRegex(KeyError, '.* does not exist'):
99
+ contextual_value('f')
100
+
101
+ self.assertEqual(all_contextual_values(), dict(x=3, y=3, z=3))
102
+
103
+ # Member attributes take precedence over `contextual_override`.
104
+ self.assertEqual(a1.x, 1)
105
+ self.assertEqual(a1.y, 2)
106
+
107
+ # Override attributes take precedence over member attribute.
108
+ with a1.override(y=3):
109
+ self.assertEqual(a1.y, 3)
110
+ with a1.override(y=4):
111
+ self.assertEqual(a1.y, 4)
112
+ self.assertEqual(a1.y, 3)
113
+ self.assertEqual(a1.y, 2)
114
+
115
+ # `contextual_override` takes precedence over contextual default.
116
+ self.assertEqual(a1.z, 3)
117
+
118
+ # Test nested contextual override with override_attrs=True (default).
119
+ with contextual_override(
120
+ y=4, z=4, override_attrs=True) as nested_override:
121
+ self.assertEqual(
122
+ nested_override,
123
+ dict(
124
+ x=ContextualOverride(3, cascade=False, override_attrs=False),
125
+ y=ContextualOverride(4, cascade=False, override_attrs=True),
126
+ z=ContextualOverride(4, cascade=False, override_attrs=True),
127
+ ),
128
+ )
129
+
130
+ # Member attribute is not overriden as current scope does not override
131
+ # `x``.
132
+ self.assertEqual(a1.x, 1)
133
+
134
+ # Member attribute is overriden.
135
+ self.assertEqual(a1.y, 4)
136
+
137
+ # `ContextualObject.override` takes precedence over
138
+ # `contextual_override(override_attrs=True)`.
139
+ with a1.override(y=3):
140
+ self.assertEqual(a1.y, 3)
141
+ self.assertEqual(a1.y, 4)
142
+
143
+ # Member default is overriden.
144
+ self.assertEqual(a1.z, 4)
145
+
146
+ self.assertEqual(a1.y, 2)
147
+ self.assertEqual(a1.z, 3)
148
+
149
+ self.assertEqual(a1.y, 2)
150
+ self.assertEqual(a1.z, -1)
151
+
152
+ def test_context_cascade(self):
153
+ class A(ContextualObject):
154
+ x: int
155
+ y: int = contextual_attribute()
156
+ z: int = contextual_attribute(default=-1)
157
+
158
+ a = A(1, 2)
159
+ self.assertEqual(a.x, 1)
160
+ self.assertEqual(a.y, 2)
161
+ self.assertEqual(a.z, -1)
162
+
163
+ with contextual_override(x=3, y=3, z=3, cascade=True):
164
+ self.assertEqual(a.x, 1)
165
+ self.assertEqual(a.y, 2)
166
+ self.assertEqual(a.z, 3)
167
+
168
+ # Outter `pg.contextual_override` takes precedence
169
+ # over inner `pg.contextual_override` when cascade=True.
170
+ with contextual_override(y=4, z=4, cascade=True):
171
+ self.assertEqual(a.x, 1)
172
+ self.assertEqual(a.y, 2)
173
+ self.assertEqual(a.z, 3)
174
+
175
+ with contextual_override(y=4, z=4, override_attrs=True):
176
+ self.assertEqual(a.x, 1)
177
+ self.assertEqual(a.y, 2)
178
+ self.assertEqual(a.z, 3)
179
+
180
+ self.assertEqual(a.x, 1)
181
+ self.assertEqual(a.y, 2)
182
+ self.assertEqual(a.z, -1)
183
+
184
+ with contextual_override(x=3, y=3, z=3, cascade=True, override_attrs=True):
185
+ self.assertEqual(a.x, 3)
186
+ self.assertEqual(a.y, 3)
187
+ self.assertEqual(a.z, 3)
188
+
189
+ with contextual_override(y=4, z=4, override_attrs=True):
190
+ self.assertEqual(a.x, 3)
191
+ self.assertEqual(a.y, 3)
192
+ self.assertEqual(a.z, 3)
193
+
194
+ self.assertEqual(a.x, 1)
195
+ self.assertEqual(a.y, 2)
196
+ self.assertEqual(a.z, -1)
197
+
198
+ def test_sym_inferred(self):
199
+ class A(ContextualObject):
200
+ x: int = 1
201
+ y: int = contextual_attribute()
202
+
203
+ a = A()
204
+ with self.assertRaisesRegex(
205
+ AttributeError, '.* is not found under its context'):
206
+ _ = a.sym_inferred('y')
207
+ self.assertIsNone(a.sym_inferred('y', default=None))
208
+
209
+ with self.assertRaises(AttributeError):
210
+ _ = a.sym_inferred('z')
211
+ self.assertIsNone(a.sym_inferred('z', default=None))
212
+
213
+ def test_weak_ref(self):
214
+ class A(ContextualObject):
215
+ x: int = 1
216
+
217
+ a = A()
218
+ self.assertIsNotNone(weakref.ref(a))
219
+
220
+
221
+ class ContextualAttributeTest(unittest.TestCase):
222
+ """Tests for Component."""
223
+
224
+ def test_contextualibute_access(self):
225
+
226
+ class A(ContextualObject):
227
+ x: int
228
+ y: int = contextual_attribute()
229
+
230
+ # Not okay: `A.x` is required.
231
+ with self.assertRaisesRegex(TypeError, 'missing 1 required argument'):
232
+ _ = A()
233
+
234
+ # Okay: `A.y` is contextual.
235
+ a = A(1)
236
+
237
+ # `a.y` is not yet available from the context.
238
+ with self.assertRaises(AttributeError):
239
+ _ = a.y
240
+
241
+ class B(ContextualObject):
242
+ # Attributes with annotation will be treated as symbolic fields.
243
+ p: int
244
+ q: A = A(2)
245
+ z: int = contextual_attribute()
246
+
247
+ class C(ContextualObject):
248
+ a: int
249
+ b: B = B(2)
250
+ y: int = 1
251
+ z = 2
252
+
253
+ c = C(1)
254
+ b = c.b
255
+ a = b.q
256
+
257
+ # Test symbolic attributes declared from C.
258
+ self.assertTrue(c.sym_hasattr('a'))
259
+ self.assertTrue(c.sym_hasattr('b'))
260
+ self.assertTrue(c.sym_hasattr('y'))
261
+ self.assertFalse(c.sym_hasattr('z'))
262
+
263
+ # Contextual access to c.y from a.
264
+ self.assertEqual(a.y, 1)
265
+ self.assertEqual(b.z, 2)
266
+
267
+ # 'y' is not defined as an attribute in 'B'.
268
+ with self.assertRaises(AttributeError):
269
+ _ = b.y
270
+
271
+ c.rebind(y=2)
272
+ self.assertEqual(c.y, 2)
273
+ self.assertEqual(a.y, 2)
274
+
275
+ c.z = 3
276
+ self.assertEqual(c.z, 3)
277
+ self.assertEqual(b.z, 3)
278
+
279
+ def test_to_html(self):
280
+ class A(ContextualObject):
281
+ x: int = 1
282
+ y: int = contextual_attribute()
283
+
284
+ def assert_content(html, expected):
285
+ expected = inspect.cleandoc(expected).strip()
286
+ actual = html.content.strip()
287
+ if actual != expected:
288
+ print(actual)
289
+ self.assertEqual(actual.strip(), expected)
290
+
291
+ self.assertIn(
292
+ inspect.cleandoc(
293
+ """
294
+ .contextual-attribute {
295
+ color: purple;
296
+ }
297
+ .unavailable-contextual {
298
+ color: gray;
299
+ font-style: italic;
300
+ }
301
+ """
302
+ ),
303
+ A().to_html().style_section,
304
+ )
305
+
306
+ assert_content(
307
+ A().to_html(enable_summary_tooltip=False),
308
+ """
309
+ <details open class="pyglove a"><summary><div class="summary-title">A(...)</div></summary><div class="complex-value a"><details open class="pyglove int"><summary><div class="summary-name">x<span class="tooltip">x</span></div><div class="summary-title">int</div></summary><span class="simple-value int">1</span></details><details open class="pyglove contextual-attribute"><summary><div class="summary-name">y<span class="tooltip">y</span></div><div class="summary-title">ContextualAttribute(...)</div></summary><div class="unavailable-contextual">(not available)</div></details></div></details>
310
+ """
311
+ )
312
+
313
+ class B(ContextualObject):
314
+ z: Any
315
+ y: int = 2
316
+
317
+ b = B(A())
318
+ assert_content(
319
+ b.z.to_html(enable_summary_tooltip=False),
320
+ """
321
+ <details open class="pyglove a"><summary><div class="summary-title">A(...)</div></summary><div class="complex-value a"><details open class="pyglove int"><summary><div class="summary-name">x<span class="tooltip">x</span></div><div class="summary-title">int</div></summary><span class="simple-value int">1</span></details><details open class="pyglove contextual-attribute"><summary><div class="summary-name">y<span class="tooltip">y</span></div><div class="summary-title">ContextualAttribute(...)</div></summary><span class="simple-value int">2</span></details></div></details>
322
+ """
323
+ )
324
+
325
+
326
+ if __name__ == '__main__':
327
+ unittest.main()
@@ -155,6 +155,14 @@ from pyglove.core.utils.error_utils import ErrorInfo
155
155
  from pyglove.core.utils.timing import timeit
156
156
  from pyglove.core.utils.timing import TimeIt
157
157
 
158
+ # Value override from context manager.
159
+ from pyglove.core.utils.contextual import ContextualOverride
160
+ from pyglove.core.utils.contextual import contextual_override
161
+ from pyglove.core.utils.contextual import with_contextual_override
162
+ from pyglove.core.utils.contextual import get_contextual_override
163
+ from pyglove.core.utils.contextual import contextual_value
164
+ from pyglove.core.utils.contextual import all_contextual_values
165
+
158
166
  # Text color.
159
167
  from pyglove.core.utils.text_color import colored
160
168
  from pyglove.core.utils.text_color import colored_block
@@ -0,0 +1,147 @@
1
+ # Copyright 2025 The PyGlove Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Injecting and manipulating values through context managers."""
15
+
16
+ import contextlib
17
+ import dataclasses
18
+ import threading
19
+ from typing import Any, Callable, ContextManager, Iterator, Optional
20
+
21
+ from pyglove.core.utils import missing
22
+
23
+ RAISE_IF_HAS_ERROR = (missing.MISSING_VALUE,)
24
+ _TLS_KEY_CONTEXTUAL_OVERRIDES = '__contextual_overrides__'
25
+ _global_contextual_overrides = threading.local()
26
+
27
+
28
+ @dataclasses.dataclass(frozen=True)
29
+ class ContextualOverride:
30
+ """Value marker for contextual override for an attribute."""
31
+
32
+ # Overridden value.
33
+ value: Any
34
+
35
+ # If True, this override will apply to both current scope and nested scope,
36
+ # meaning current `pg.contextual_override` will take precedence over all
37
+ # nested `pg.contextual_override` on this attribute.
38
+ cascade: bool = False
39
+
40
+ # If True, this override will apply to attributes that already have values.
41
+ override_attrs: bool = False
42
+
43
+
44
+ def contextual_override(
45
+ *,
46
+ cascade: bool = False,
47
+ override_attrs: bool = False,
48
+ **variables,
49
+ ) -> ContextManager[dict[str, ContextualOverride]]:
50
+ """Context manager to provide contextual values under a scope.
51
+
52
+ Please be aware that contextual value override are per-thread. If you want
53
+ to propagate the contextual value override to other threads, please obtain
54
+ a wrapper function for a user function using
55
+ `pg.with_contextual_override(func)`.
56
+
57
+ Args:
58
+ cascade: If True, this override will apply to both current scope and nested
59
+ scope, meaning that this `pg.contextual_override` will take precedence
60
+ over all nested `pg.contextual_override` on the overriden variables.
61
+ override_attrs: If True, this override will apply to attributes that already
62
+ have values. Otherwise overridden variables will only be used for
63
+ contextual attributes whose values are not present.
64
+ **variables: Key/values as override for contextual attributes.
65
+
66
+ Returns:
67
+ A dict of attribute names to their contextual overrides.
68
+ """
69
+ vs = {}
70
+ for k, v in variables.items():
71
+ if not isinstance(v, ContextualOverride):
72
+ v = ContextualOverride(v, cascade, override_attrs)
73
+ vs[k] = v
74
+ return contextual_scope(_global_contextual_overrides, **vs)
75
+
76
+
77
+ def with_contextual_override(func: Callable[..., Any]) -> Callable[..., Any]:
78
+ """Wraps a user function with the access to the current contextual override.
79
+
80
+ The wrapped function can be called from another thread.
81
+
82
+ Args:
83
+ func: The user function to be wrapped.
84
+
85
+ Returns:
86
+ A wrapper function that have the access to the current contextual override,
87
+ which can be called from another thread.
88
+ """
89
+ with contextual_override() as current_context:
90
+ pass
91
+
92
+ def _func(*args, **kwargs) -> Any:
93
+ with contextual_override(**current_context):
94
+ return func(*args, **kwargs)
95
+
96
+ return _func
97
+
98
+
99
+ def get_contextual_override(var_name: str) -> Optional[ContextualOverride]:
100
+ """Returns the overriden contextual value in current scope."""
101
+ return get_scoped_value(_global_contextual_overrides, var_name)
102
+
103
+
104
+ def contextual_value(var_name: str, default: Any = RAISE_IF_HAS_ERROR) -> Any:
105
+ """Returns the value of a variable defined in `pg.contextual_override`."""
106
+ override = get_contextual_override(var_name)
107
+ if override is None:
108
+ if default == RAISE_IF_HAS_ERROR:
109
+ raise KeyError(f'{var_name!r} does not exist in current context.')
110
+ return default
111
+ return override.value
112
+
113
+
114
+ def all_contextual_values() -> dict[str, Any]:
115
+ """Returns all values provided from `pg.contextual_override` in scope."""
116
+ overrides = getattr(
117
+ _global_contextual_overrides, _TLS_KEY_CONTEXTUAL_OVERRIDES, {}
118
+ )
119
+ return {k: v.value for k, v in overrides.items()}
120
+
121
+
122
+ @contextlib.contextmanager
123
+ def contextual_scope(
124
+ tls: threading.local, **variables
125
+ ) -> Iterator[dict[str, ContextualOverride]]:
126
+ """Context manager to set variables within a scope."""
127
+ previous_values = getattr(tls, _TLS_KEY_CONTEXTUAL_OVERRIDES, {})
128
+ current_values = dict(previous_values)
129
+ for k, v in variables.items():
130
+ old_v = current_values.get(k, None)
131
+ if old_v and old_v.cascade:
132
+ v = old_v
133
+ current_values[k] = v
134
+ try:
135
+ setattr(tls, _TLS_KEY_CONTEXTUAL_OVERRIDES, current_values)
136
+ yield current_values
137
+ finally:
138
+ setattr(tls, _TLS_KEY_CONTEXTUAL_OVERRIDES, previous_values)
139
+
140
+
141
+ def get_scoped_value(
142
+ tls: threading.local, var_name: str, default: Any = None
143
+ ) -> ContextualOverride:
144
+ """Gets the value for requested variable from current scope."""
145
+ scoped_values = getattr(tls, _TLS_KEY_CONTEXTUAL_OVERRIDES, {})
146
+ return scoped_values.get(var_name, default)
147
+
@@ -0,0 +1,88 @@
1
+ # Copyright 2025 The PyGlove Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import concurrent.futures
15
+ import unittest
16
+ from pyglove.core.utils import contextual
17
+
18
+
19
+ class ContextualTest(unittest.TestCase):
20
+
21
+ def test_contextual_override(self):
22
+ with contextual.contextual_override(x=3, y=3, z=3) as parent_override:
23
+ self.assertEqual(
24
+ parent_override,
25
+ dict(
26
+ x=contextual.ContextualOverride(
27
+ 3, cascade=False, override_attrs=False
28
+ ),
29
+ y=contextual.ContextualOverride(
30
+ 3, cascade=False, override_attrs=False
31
+ ),
32
+ z=contextual.ContextualOverride(
33
+ 3, cascade=False, override_attrs=False
34
+ ),
35
+ ),
36
+ )
37
+ self.assertEqual(
38
+ contextual.get_contextual_override('y'),
39
+ contextual.ContextualOverride(3, cascade=False, override_attrs=False),
40
+ )
41
+ self.assertEqual(contextual.contextual_value('x'), 3)
42
+ self.assertIsNone(contextual.contextual_value('f', None))
43
+ with self.assertRaisesRegex(KeyError, '.* does not exist'):
44
+ contextual.contextual_value('f')
45
+
46
+ self.assertEqual(contextual.all_contextual_values(), dict(x=3, y=3, z=3))
47
+
48
+ # Test nested contextual override with override_attrs=True (default).
49
+ with contextual.contextual_override(
50
+ y=4, z=4, override_attrs=True) as nested_override:
51
+ self.assertEqual(
52
+ nested_override,
53
+ dict(
54
+ x=contextual.ContextualOverride(
55
+ 3, cascade=False, override_attrs=False
56
+ ),
57
+ y=contextual.ContextualOverride(
58
+ 4, cascade=False, override_attrs=True
59
+ ),
60
+ z=contextual.ContextualOverride(
61
+ 4, cascade=False, override_attrs=True
62
+ ),
63
+ ),
64
+ )
65
+
66
+ # Test nested contextual override with cascade=True.
67
+ with contextual.contextual_override(x=3, y=3, z=3, cascade=True):
68
+ with contextual.contextual_override(y=4, z=4, cascade=True):
69
+ self.assertEqual(contextual.contextual_value('x'), 3)
70
+ self.assertEqual(contextual.contextual_value('y'), 3)
71
+ self.assertEqual(contextual.contextual_value('z'), 3)
72
+
73
+ def test_with_contextual_override(self):
74
+ def func(i):
75
+ del i
76
+ return contextual.contextual_value('x')
77
+
78
+ pool = concurrent.futures.ThreadPoolExecutor()
79
+ with contextual.contextual_override(x=3):
80
+ self.assertEqual(contextual.with_contextual_override(func)(0), 3)
81
+ self.assertEqual(
82
+ list(pool.map(contextual.with_contextual_override(func), range(1))),
83
+ [3]
84
+ )
85
+
86
+
87
+ if __name__ == '__main__':
88
+ unittest.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: pyglove
3
- Version: 0.4.5.dev202501150808
3
+ Version: 0.4.5.dev202501160808
4
4
  Summary: PyGlove: A library for manipulating Python objects.
5
5
  Home-page: https://github.com/google/pyglove
6
6
  Author: PyGlove Authors
@@ -1,5 +1,5 @@
1
1
  pyglove/__init__.py,sha256=YPUWALRDu4QuI7N3TUmVaVr513hUt0qXrjY582I1q5c,1352
2
- pyglove/core/__init__.py,sha256=629Ml4RzdBdtd_1Cz4HZoCde_ilOG2lAW02E90hStWw,9333
2
+ pyglove/core/__init__.py,sha256=BF-8v1D5lTBAo4vlpDt0qyOG9NQ71oh_UfthBVrPaN4,9614
3
3
  pyglove/core/logging.py,sha256=Sr5nLyUQmc4CAEYAq8qbP3ghpjmpz2sOuhq2A0tgQ6I,2456
4
4
  pyglove/core/logging_test.py,sha256=3z_c6wnxbqDbwUmSOAZzeDPXvzoweYL5QHUQVMJ5Xgo,1917
5
5
  pyglove/core/coding/__init__.py,sha256=tuHIg19ZchtkOQbdFVTVLkUpBa5f1eo66XtnKw3lcIU,1645
@@ -65,7 +65,7 @@ pyglove/core/patching/pattern_based.py,sha256=UtSNB-ARNqVjXwZovjVi84QEoXUGLLBTgL
65
65
  pyglove/core/patching/pattern_based_test.py,sha256=PW1EcVfsFPB6wtgwg3s4dzvigWn3b5S8eMNGo0SJiZ0,2771
66
66
  pyglove/core/patching/rule_based.py,sha256=JAQp8mWeIOxwIdqusA3GmXia-fxQhQsxbUTmE329wF8,17038
67
67
  pyglove/core/patching/rule_based_test.py,sha256=qfy0ILmczV_LMHWEnwo2y079OrJsGYO0nKxSZdmIUcI,18782
68
- pyglove/core/symbolic/__init__.py,sha256=jYq-LwR1Ql3iMChjz9lN-0heDKiocmxR0ZJFEJ8RHHQ,5787
68
+ pyglove/core/symbolic/__init__.py,sha256=JZvyaEcS1QxA8MaAGANBWMmRTQcGk_6F0kjFxjokJqg,6002
69
69
  pyglove/core/symbolic/base.py,sha256=aSZPSk7v3Niv6D1HfL_JEEXfI-U1cQnTxJxY9wXem54,77627
70
70
  pyglove/core/symbolic/base_test.py,sha256=yASIHIuWiUB1jf4nN-Y4XOjyvr8eQfRpr7s_1LZsu78,7188
71
71
  pyglove/core/symbolic/boilerplate.py,sha256=sQ3G25r5bo_UmIdjreL4jkAuQCXIHVlvUfGjjkNod6Y,5955
@@ -74,6 +74,8 @@ pyglove/core/symbolic/class_wrapper.py,sha256=xQiMh5vFlOQ76tbqsF5UWEghvU4d9UmvbN
74
74
  pyglove/core/symbolic/class_wrapper_test.py,sha256=GPgeLefIPj9hiD0ib6z2LyOm6A3O2f4-JHpE7dgfsNM,21644
75
75
  pyglove/core/symbolic/compounding.py,sha256=gvOodZ2gWHA0jNdwt8yvnRsPkHQDXDb5s88Uwp6DAqs,11703
76
76
  pyglove/core/symbolic/compounding_test.py,sha256=hOzrIROvajUTtPm0SUbEsEV4C1bXanhAoHinHrjZoXw,8320
77
+ pyglove/core/symbolic/contextual_object.py,sha256=ar9Q_0P0HHbDf8kLHpS8GFZEMCRuCCB6DP18iGItiiw,9146
78
+ pyglove/core/symbolic/contextual_object_test.py,sha256=wA5xfIhEHOC9qE3bbiA59CAPxWs9AVPaNiKEoprkWpQ,10209
77
79
  pyglove/core/symbolic/dict.py,sha256=7IxKSjUsGulUcNk3xqQnJ2ubGNUbqcc0ZFe8cKiigKA,36931
78
80
  pyglove/core/symbolic/dict_test.py,sha256=3MATsFw9Ci0jVPbAT2ivKVZ3PCnBBBvbkMWKgpgl-Fk,72915
79
81
  pyglove/core/symbolic/diff.py,sha256=zHfED0Bbq8G_HWNPj3vrOCWzt_062rFhx3BMlpCb9oo,16282
@@ -127,9 +129,11 @@ pyglove/core/typing/typed_missing.py,sha256=-l1omAu0jBZv5BnsFYXBqfvQwVBnmPh_X1wc
127
129
  pyglove/core/typing/typed_missing_test.py,sha256=TCNsb1SRpFaVdxYn2mB_yaLuja8w5Qn5NP7uGiZVBWs,2301
128
130
  pyglove/core/typing/value_specs.py,sha256=Yxdrz4aURMBrtqUW4to-2Vptc6Z6oqQrLyMBiAZt2bc,102302
129
131
  pyglove/core/typing/value_specs_test.py,sha256=MsScWDRaN_8pfRDO9MCp9HdUHVm_8wHWyKorWVSnhE4,127165
130
- pyglove/core/utils/__init__.py,sha256=cegrJtHy0h7DIUFcQN67TZJf9_f28OR-NrKbKKjPkeE,8183
132
+ pyglove/core/utils/__init__.py,sha256=I2bRTzigU7qJVEATGlLUFkYzkiCBBCCEwrQyhsrRNmI,8602
131
133
  pyglove/core/utils/common_traits.py,sha256=PWxOgPhG5H60ZwfO8xNAEGRjFUqqDZQBWQYomOfvdy8,3640
132
134
  pyglove/core/utils/common_traits_test.py,sha256=DIuZB_1xfmeTVfWnGOguDQcDAM_iGgBOe8C-5CsIqBc,1122
135
+ pyglove/core/utils/contextual.py,sha256=RxBQkDM2gB6QwZj_2oMels6oh-zQPGJJlinZbbqHuYQ,5148
136
+ pyglove/core/utils/contextual_test.py,sha256=OOcthquVyAekTqt1RyYcEMHaockMIokpbv4pSf13Nzs,3252
133
137
  pyglove/core/utils/docstr_utils.py,sha256=5BY40kXozPKVGOB0eN8jy1P5_GHIzqFJ9FXAu_kzxaw,5119
134
138
  pyglove/core/utils/docstr_utils_test.py,sha256=i33VT6zHXEuIIJ4PPg1bVSfaYSnUsC8yST_NfpT-Uds,4228
135
139
  pyglove/core/utils/error_utils.py,sha256=ACIqtq4hsWrV00Gxd1OyeHCI-obGBR6J3H9VI1Y9clM,5780
@@ -207,8 +211,8 @@ pyglove/ext/scalars/randoms.py,sha256=LkMIIx7lOq_lvJvVS3BrgWGuWl7Pi91-lA-O8x_gZs
207
211
  pyglove/ext/scalars/randoms_test.py,sha256=nEhiqarg8l_5EOucp59CYrpO2uKxS1pe0hmBdZUzRNM,2000
208
212
  pyglove/ext/scalars/step_wise.py,sha256=IDw3tuTpv0KVh7AN44W43zqm1-E0HWPUlytWOQC9w3Y,3789
209
213
  pyglove/ext/scalars/step_wise_test.py,sha256=TL1vJ19xVx2t5HKuyIzGoogF7N3Rm8YhLE6JF7i0iy8,2540
210
- pyglove-0.4.5.dev202501150808.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
211
- pyglove-0.4.5.dev202501150808.dist-info/METADATA,sha256=djfHeOlrh9nRfIY2ZQghYSlCVa_bBXxNOpjHCXPcpwE,7067
212
- pyglove-0.4.5.dev202501150808.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
213
- pyglove-0.4.5.dev202501150808.dist-info/top_level.txt,sha256=wITzJSKcj8GZUkbq-MvUQnFadkiuAv_qv5qQMw0fIow,8
214
- pyglove-0.4.5.dev202501150808.dist-info/RECORD,,
214
+ pyglove-0.4.5.dev202501160808.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
215
+ pyglove-0.4.5.dev202501160808.dist-info/METADATA,sha256=fTXf2BQZaeemr718pJMTGLUvFZDyJFUa224Kl20GJDI,7067
216
+ pyglove-0.4.5.dev202501160808.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
217
+ pyglove-0.4.5.dev202501160808.dist-info/top_level.txt,sha256=wITzJSKcj8GZUkbq-MvUQnFadkiuAv_qv5qQMw0fIow,8
218
+ pyglove-0.4.5.dev202501160808.dist-info/RECORD,,