pg.Ref¶
Accessible via pg.Ref
, pg.symbolic.Ref
.
- class Ref(value, **kwargs)[source]¶
Bases:
pg.Object
,pg.Inferentiable
Symbolic reference.
When adding a symbolic node to a symbolic tree, it undergoes a copy operation if it already has a parent, ensuring that all symbolic objects have a single parent. Additionally, list and dict objects are automatically converted to
pg.List
andpg.Dict
, respectively, to enable symbolic operability.However, these two conventions come with certain costs. The act of making copies incurs a runtime cost, and it also introduces challenges in sharing states across different symbolic objects. To address this issue, symbolic reference is introduced. This feature allows a symbolic node to refer to value objects without the need for transformation or copying, even when the symbolic node itself is copied. For example:
class A(pg.Object): x: int a = pg.Ref(A(1)) b = pg.Dict(x=a) c = pg.Dict(y=a) assert b.x is a assert c.y is a assert b.clone().x is a assert c.clone(deep=True).y is a
In this example,
pg.Ref
is used to create a symbolic reference to the objectA(1)
, and thepg.Dict
objects b and c can then reference a without creating additional copies. This mechanism not only mitigates the runtime cost but also facilitates seamless sharing of states among various symbolic objects.Another useful scenario arises when we wish to utilize regular Python list and dict objects. In this case,
pg.Ref
enables us to access the list/dict object as fields in the symbolic tree without requiring them to be transformed intopg.List
andpg.Dict
. This allows for seamless integration of standard Python containers within the symbolic structure:d = pg.Dict(x=pg.Ref({1: 2})) assert isinstance(d.x, dict) assert not isinstance(d.x, pg.Dict) e = pg.Dict(x=pg.Ref([0, 1, 2]])) assert isinstance(e.x, list) assert not isinstance(e.x, pg.List)
Please be aware that
pg.Ref
objects are treated as leaf nodes in the symbolic tree, even when they reference other symbolic objects. As a result, therebind()
method cannot modify the value they are pointing to.For primitive types,
pg.Ref()
returns their values directly without creating a reference. For example,pg.Ref(1)
andpg.Ref('abc')
will simply return the values 1 and ‘abc’, respectively, without any additional referencing.Methods:
custom_apply
(path, value_spec[, ...])Validate candidates during value_spec binding time.
format
([compact, verbose, root_indent, markdown])Formats this object.
infer
(**kwargs)Returns the referenced value.
sym_eq
(other)Tests symbolic equality.
sym_jsonify
(**kwargs)Converts current object to a dict of plain Python objects.
Attributes:
Returns the referenced value.
- custom_apply(path, value_spec, allow_partial=False, child_transform=None)[source]¶
Validate candidates during value_spec binding time.
- format(compact=False, verbose=False, root_indent=0, *, markdown=False, **kwargs)[source]¶
Formats this object.
- Return type: