pygx.topology¶
Tree topology and JSON serialization primitives shared across PyGX.
topology
¶
Tree topology and JSON serialization primitives shared across PyGX.
pygx.topology defines the value-space vocabulary that other layers build on:
KeyPath/KeyPathSetaddress nodes inside a nested structure, andmessage_on_pathproduces path-tagged error messages.MissingValueand theMISSING_VALUEsentinel mark unbound fields.MaybePartialis the partiality interface implemented by every symbolic value.traverse,transform,flatten,canonicalize,merge, andmerge_treewalk and rewrite (maybe-)hierarchical Python values keyed byKeyPath.
JSON serialization for these structures lives in pygx.wire.
MaybePartial
¶
Interface for classes whose instances can be partially constructed.
A MaybePartial object is an object whose __init__ method can accept
pg.MISSING_VALUE as its argument values. All symbolic types (see
pygx.Symbolic) implements this interface, as their symbolic
attributes can be partially filled.
Example::
d = pg.Dict(x=pg.MISSING_VALUE, y=1) assert d.sym_partial assert 'x' in d.sym_missing()
sym_partial
property
¶
Returns True if this object is partial. Otherwise False.
An object is considered partial when any of its required fields is missing, or at least one member is partial. The subclass can override this method to provide a more efficient solution.
sym_missing
abstractmethod
¶
Returns missing values from this object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flatten
|
bool
|
If True, convert nested structures into a flattened dict using key path (delimited by '.' and '[]') as key. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str | int, Any]
|
A dict of key to MISSING_VALUE. |
Source code in pygx/topology/_maybe_partial.py
MissingValue
¶
KeyPath
¶
KeyPath(
key_or_key_list: Any | list[Any] | None = None,
parent: Optional[KeyPath] = None,
)
Bases: Formattable, WireConvertible
Represents a path of keys from the root to a node in a tree.
KeyPath is an important concept in PyGX, which is used for representing
a symbolic object's location (see pygx.Symbolic.sym_path) within
its symbolic tree. For example::
class A(pg.Object): x: int y: str
class B(pg.Object): z: A
a = A(x=1, y='foo')
b = B(z=a)
assert a.sym_path == 'z' # The path to object a is 'z'.
assert b.sym_path == '' # The root object's KeyPath is empty.
Since each node in a tree has a unique location, given the root we shall be
able to use a KeyPath object to locate the node. With the example
above, we can query the member x of object a via::
pg.KeyPath.parse('z.x').query(b) # Should return 1.
Similarly, we can modify a symbolic object's sub-node based on a KeyPath
object. See pygx.Symbolic.rebind for modifying sub-nodes in a
symbolic tree.
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_or_key_list
|
Any | list[Any] | None
|
A single object as key, or a list/tuple of objects as keys in the path. When string types or StrKey objects are used as key, dot ('.') is used as the delimiter, otherwise square brackets ('[]') is used as the delimiter when formatting a KeyPath. For object type key, str(object) will be used to represent the key in string form. |
None
|
parent
|
Optional[KeyPath]
|
Parent KeyPath. |
None
|
Source code in pygx/topology/_value_location.py
parent
property
¶
parent: KeyPath
The KeyPath object for current node's parent.
Example::
path = pg.KeyPath.parse('a.b.c.') assert path.parent == 'a.b'
Returns:
| Type | Description |
|---|---|
KeyPath
|
A |
Raises:
| Type | Description |
|---|---|
KeyError
|
If current path is the root. |
from_value
classmethod
¶
Returns a KeyPath object from a KeyPath equivalence.
Source code in pygx/topology/_value_location.py
parse
classmethod
¶
Creates a KeyPath object from parsing a JSONPath-like string.
The JSONPath (https://restfulapi.net/json-jsonpath/) like string is defined as following::
For example, following keys are valid path strings::
'' : An empty path representing the root of a path.
'a' : A path that contains a dict key 'a'.
'a.b' : A path that contains two dict keys 'a' and 'b'.
'a[0]' : A path that contains a dict key 'a' and a list key 0.
'a.0.' : A path that contains two dict keys 'a' and '0'.
'a[0][1]' : A path that contains a dict key 'a' and two list keys
0 and 1 for a multi-dimension list.
'a[x.y].b' : A path that contains three dict keys: 'a', 'x.y', 'b'.
Since 'x.y' has delimiter characters, it needs to be
enclosed in brackets.
TODO(daiyip): Support paring KeyPath from keys of complex types.
Now this method only supports parsing KeyPath of string and int keys.
That being said, format/parse are not symmetric, while format
can convert a KeyPath that includes complex keys into a string,
parse is not able to convert them back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path_str
|
str
|
A JSON-path-like string. |
required |
parent
|
Optional[KeyPath]
|
Parent KeyPath object. |
None
|
Returns:
| Type | Description |
|---|---|
KeyPath
|
A KeyPath object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Path string is in bad format. |
Source code in pygx/topology/_value_location.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
query
¶
Query the value from the source object based on current path.
Example::
class A(pg.Object): x: int y: str
class B(pg.Object): z: A
b = B(z=A(x=1, y='foo')) assert pg.KeyPath.parse('z.x').query(b) == 1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Any
|
Source value to query. |
required |
use_inferred
|
bool
|
If True, infer |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
Value from src if path exists. |
Raises:
| Type | Description |
|---|---|
KeyError
|
Path doesn't exist in src. |
RuntimeError
|
Called on a KeyPath that is considered as removed. |
Source code in pygx/topology/_value_location.py
get
¶
Gets the value of current path from an object with a default value.
Source code in pygx/topology/_value_location.py
exists
¶
is_relative_to
¶
is_relative_to(other: Union[int, str, KeyPath]) -> bool
Returns whether current path is relative to another path.
Source code in pygx/topology/_value_location.py
to_json
¶
Serializes to its JSONPath string (wire-convertible, round-trips).
from_json
classmethod
¶
from_json(json_value: Any, **kwargs: Any) -> KeyPath
Rebuilds a KeyPath from its serialized JSONPath string.
path_str
¶
Returns JSONPath representation of current path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preserve_complex_keys
|
bool
|
If True, complex keys such as |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Path string. |
Source code in pygx/topology/_value_location.py
KeyPathSet
¶
KeyPathSet(
paths: Iterable[str | int | KeyPath] | None = None,
*,
include_intermediate: bool = False
)
Bases: Formattable
A KeyPath set based on trie-like data structure.
Source code in pygx/topology/_value_location.py
add
¶
add(path: str | int | KeyPath, include_intermediate: bool = False) -> bool
Adds a path to the set.
Source code in pygx/topology/_value_location.py
remove
¶
remove(path: str | int | KeyPath) -> bool
Removes a path from the set.
Source code in pygx/topology/_value_location.py
has_prefix
¶
has_prefix(root_path: int | str | KeyPath) -> bool
Returns True if the set has a path with the given prefix.
Source code in pygx/topology/_value_location.py
rebase
¶
rebase(root_path: int | str | KeyPath) -> None
Returns a KeyPathSet with the given prefix path added.
Source code in pygx/topology/_value_location.py
clear
¶
copy
¶
difference_update
¶
difference_update(other: KeyPathSet) -> None
Removes the paths in the other set from the current set.
Source code in pygx/topology/_value_location.py
difference
¶
difference(other: KeyPathSet) -> Self
intersection_update
¶
intersection_update(other: KeyPathSet) -> None
Removes the paths in the other set from the current set.
Source code in pygx/topology/_value_location.py
intersection
¶
intersection(other: KeyPathSet) -> Self
update
¶
update(other: KeyPathSet) -> None
Updates the current set with the other set.
Source code in pygx/topology/_value_location.py
union
¶
union(other: KeyPathSet, copy: bool = False) -> Self
subtree
¶
subtree(root_path: int | str | KeyPath) -> Optional[KeyPathSet]
Returns the relative paths of the sub-tree rooted at the given path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_path
|
int | str | KeyPath
|
A KeyPath for the root of the sub-tree. |
required |
Returns:
| Type | Description |
|---|---|
Optional[KeyPathSet]
|
A KeyPathSet that contains all the child paths of the given root path. |
Optional[KeyPathSet]
|
Please note that the returned value share the same trie as the current |
Optional[KeyPathSet]
|
value. So addition/removal of paths in the returned value will also |
Optional[KeyPathSet]
|
affect the current value. If there is no child path under the given root |
Optional[KeyPathSet]
|
path, None will be returned. |
Source code in pygx/topology/_value_location.py
format
¶
from_value
classmethod
¶
from_value(
value: Union[Iterable[int | str | KeyPath], KeyPathSet],
include_intermediate: bool = False,
)
Returns a KeyPathSet from a compatible value.
Source code in pygx/topology/_value_location.py
StrKey
¶
Interface for classes whose instances can be treated as str in KeyPath.
A pygx.KeyPath will format the path string using . (dot) as
the delimiter for a key represented by this object. Otherwise [] (square
brackets) will be used as the delimiters.
Example::
class MyKey(pg.utils.StrKey):
def __init__(self, name):
self.name = name
def __str__(self):
return f'__{self.name}__'
path = pg.KeyPath(['a', MyKey('b')]) print(str(path)) # Should print "a.b"
canonicalize
¶
Canonicalize (maybe) non-canonical hierarchical value.
Non-canonical hierarchical values are dicts or nested structures of dicts
that contain keys with '.' or '[
For example::
[1, {
"a.b[0]": {
"e.f": 1
}
"a.b[0].c[x.y].d": 10
}]
will result in::
[1, {
"a": {
"b": [{
"c": {
"x.y": {
"d": 10
}
}
"e": {
"f": 1
}
}]
}
}]
A sparse array indexer can be used in a non-canonical form. e.g::
{ 'a[1]': 123, 'a[5]': 234 }
This is to accommodate scenarios of list element update/append.
When sparse_list_as_dict is set to true (by default), dict above will be
converted to::
{ 'a': [123, 234] }
Otherwise sparse indexer will be kept so the container type will remain as a dict::
{ 'a': { 1: 123, 5: 234 } }
(Please note that sparse indexer as key is not JSON serializable.)
This is the reverse operation of method flatten. If input value is a simple type, the value itself will be returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Any
|
A simple type or a nested structure of dict that may contain keys with JSON paths like 'a.b.c'. |
required |
sparse_list_as_dict
|
bool
|
Whether to convert sparse list to dict. When this is set to True, indices specified in the key path will be kept. Otherwise, a list will be returned with elements ordered by indices in the path. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
A nested structure of ordered dict that has only canonicalized keys or |
Any
|
src itself if it's not a nested structure of dict. For dict of int keys |
Any
|
whose values form a perfect range(0, N) will be returned as a list. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If key is empty or the same key yields conflicting values
after resolving non-canonical paths. E.g: |
Source code in pygx/topology/_hierarchical.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
flatten
¶
Flattens a (maybe) hierarchical value into a depth-1 dict.
Example::
inputs = { 'a': { 'e': 1, 'f': [{ 'g': 2 }, { 'g[0]': 3 }], 'h': [], 'i.j': {}, }, 'b': 'hi', 'c': None } output = pg.utils.flatten(inputs) assert output == { 'a.e': 1, 'a.f[0].g': 2, 'a.f[1].g[0]': 3, 'a.h': [], 'a.i.j': {}, 'b': 'hi', 'c': None }
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Any
|
source value to flatten. |
required |
flatten_complex_keys
|
bool
|
if True, complex keys such as 'x.y' will be flattened as 'x'.'y'. For example: {'a': {'b.c': 1}} will be flattened into {'a.b.c': 1} if this flag is on, otherwise it will be flattened as {'a[b.c]': 1}. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
For primitive value types, |
Any
|
For list and dict types, an 1-depth dict will be returned. |
Any
|
For tuple, a tuple of the same length, with each element flattened will be |
Any
|
returned. The order of keys in nested ordered dict will be preserved, |
Any
|
Keys of different depth are joined into a string using "." for dict |
Any
|
properties and "[]" for list elements. |
Any
|
For example, if src is:: { "a": { "b": 4, "c": {"d": 10}, "e": [1, 2] 'f': [], 'g.h': {}, } } |
Any
|
then the output dict is:: { "a.b": 4, "a.c.d": 10, "a.e[0]": 1, "a.e[1]": 2, "a.f": [], "a.g.h": {}, } |
Any
|
when { "a.b": 4, "a.c.d": 10, "a.e[0]": 1, "a.e[1]": 2, "a.f": [], "a.[g.h]": {}, } |
Any
|
when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any key from the nested dictionary contains ".". |
Source code in pygx/topology/_hierarchical.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
is_partial
¶
Returns True if a value is partially bound.
Source code in pygx/topology/_hierarchical.py
merge
¶
merge(
value_list: list[Any],
merge_fn: Callable[[KeyPath, Any, Any], Any] | None = None,
) -> Any
Merge a list of hierarchical values.
Example::
original = { 'a': 1, 'b': 2, 'c': { 'd': 'foo', 'e': 'bar' } } patch = { 'b': 3, 'd': [1, 2, 3], 'c': { 'e': 'bar2', 'f': 10 } } output = pg.utils.merge([original, patch]) assert output == { 'a': 1, # b is updated. 'b': 3, 'c': { 'd': 'foo', # e is updated. 'e': 'bar2', # f is added. 'f': 10 }, # d is inserted. 'd': [1, 2, 3] })
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_list
|
list[Any]
|
A list of hierarchical values to merge. Later value will be treated as updates if it's a dict or otherwise a replacement of former value. The merge process will keep input values intact. |
required |
merge_fn
|
Callable[[KeyPath, Any, Any], Any] | None
|
A function to handle value merge that will be called for updated
or added keys. If a branch is added/updated, the root of branch will be
passed to merge_fn. the signature of function is: |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A merged value. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
KeyError
|
If new key is found while not allowed. |
Source code in pygx/topology/_hierarchical.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
merge_tree
¶
merge_tree(
dest: Any,
src: Any,
merge_fn: Callable[[KeyPath, Any, Any], Any] | None = None,
root_path: KeyPath | None = None,
) -> Any
Deep merge two (maybe) hierarchical values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dest
|
Any
|
Destination value. |
required |
src
|
Any
|
Source value. When source value is a dict, it's considered as a patch (delta) to the destination when destination is a dict or list. For other source types, it's considered as a new value that will replace dest completely. |
required |
merge_fn
|
Callable[[KeyPath, Any, Any], Any] | None
|
A function to handle value merge that will be called for updated or added keys. If a branch is added/updated, the root of branch will be passed to merge_fn. the signature of function is: (path, left_value, right_value) -> final_value If a key is only present in src dict, old_value is MISSING_VALUE. If a key is only present in dest dict, new_value is MISSING_VALUE. Otherwise both new_value and old_value are filled. If final value is MISSING_VALUE, it will be removed from its parent collection. |
None
|
root_path: KeyPath of dest.
Returns:
| Type | Description |
|---|---|
Any
|
Merged value. |
Raises:
| Type | Description |
|---|---|
KeyError
|
Dict keys are not integers when merging into a list. |
Source code in pygx/topology/_hierarchical.py
transform
¶
transform(
value: Any,
transform_fn: Callable[[KeyPath, Any], Any],
root_path: KeyPath | None = None,
inplace: bool = True,
) -> Any
Bottom-up (post-order) transform a (maybe) hierarchical value.
Transform on value is in-place unless transform_fn returns a different
instance.
Example::
def _remove_int(path, value): del path if isinstance(value, int): return pg.MISSING_VALUE return value
inputs = { 'a': { 'b': 1, 'c': [1, 'bar', 2, 3], 'd': 'foo' }, 'e': 'bar', 'f': 4 } output = pg.utils.transform(inputs, _remove_int) assert output == { 'a': { 'c': ['bar'], 'd': 'foo', }, 'e': 'bar' })
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Any python value type. If value is a list of dict, transformation will occur recursively. |
required |
transform_fn
|
Callable[[KeyPath, Any], Any]
|
Transform function in signature (path, value) -> new value If new value is MISSING_VALUE, key will be deleted. |
required |
root_path
|
KeyPath | None
|
KeyPath of the root. |
None
|
inplace
|
bool
|
If True, perform transformation in place. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Transformed value. |
Source code in pygx/topology/_hierarchical.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
traverse
¶
traverse(
value: Any,
preorder_visitor_fn: Callable[[KeyPath, Any], bool] | None = None,
postorder_visitor_fn: Callable[[KeyPath, Any], bool] | None = None,
root_path: KeyPath | None = None,
) -> bool
Traverse a (maybe) hierarchical value.
Example::
def preorder_visit(path, value): print(path)
tree = {'a': [{'c': [1, 2]}, {'d': {'g': (3, 4)}}], 'b': 'foo'} pg.utils.traverse(tree, preorder_visit)
# Should print: # 'a' # 'a[0]' # 'a[0].c' # 'a[0].c[0]' # 'a[0].c[1]' # 'a[1]' # 'a[1].d' # 'a[1].d.g' # 'b'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
A maybe hierarchical value to traverse. |
required |
preorder_visitor_fn
|
Callable[[KeyPath, Any], bool] | None
|
Preorder visitor function. Function signature is (path, value) -> should_continue. |
None
|
postorder_visitor_fn
|
Callable[[KeyPath, Any], bool] | None
|
Postorder visitor function. Function signature is (path, value) -> should_continue. |
None
|
root_path
|
KeyPath | None
|
The key path of the root value. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
Whether visitor function returns True on all nodes. |
Source code in pygx/topology/_hierarchical.py
try_listify_dict_with_int_keys
¶
try_listify_dict_with_int_keys(
src: dict[Any, Any], convert_when_sparse: bool = False
) -> tuple[list[Any] | dict[Any, Any], bool]
Try to convert a dictionary with consequentive integer keys to a list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
dict[Any, Any]
|
A dict whose keys may be int type and their range form a perfect range(0, N) list unless convert_when_sparse is set to True. |
required |
convert_when_sparse
|
bool
|
When src is a int-key dict, force convert it to a list ordered by key, even it's sparse. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[list[Any] | dict[Any, Any], bool]
|
converted list or src unchanged. |
Source code in pygx/topology/_hierarchical.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2