pg.query

Accessible via pg.query, pg.symbolic.query.

query(x, path_regex=None, where=None, enter_selected=False, custom_selector=None)[source]

Queries a (maybe) symbolic value.

Example:

@pg.members([
    ('x', pg.typing.Int()),
    ('y', pg.typing.Int())
])
class A(pg.Object):
  pass

value = {
  'a1': A(x=0, y=1),
  'a2': [A(x=1, y=1), A(x=1, y=2)],
  'a3': {
    'p': A(x=2, y=1),
    'q': A(x=2, y=2)
  }
}

# Query by path regex.
# Shall print:
# {'a3.p': A(x=2, y=1)}
print(pg.query(value, r'.*p'))

# Query by value.
# Shall print:
# {
#    'a2[1].y': 2,
#    'a3.p.x': 2,
#    'a3.q.x': 2,
#    'a3.q.y': 2,
# }
print(pg.query(value, where=lambda v: v==2))

# Query by path, value and parent.
# Shall print:
# {
#    'a2[1].y': 2,
# }
print(pg.query(
    value, r'.*y',
    where=lambda v, p: v > 1 and isinstance(p, A) and p.x == 1))
Return type:

Dict[str, Any]

Parameters:
  • x – A nested structure that may contains symbolic value.

  • path_regex – Optional regex expression to constrain path.

  • where

    Optional callable to constrain value and parent when path matches with path_regex or path_regex is not provided. The signature is:

    (value) -> should_select or (value, parent) -> should_select

  • enter_selected – If True, if a node is selected, enter the node and query its sub-nodes.

  • custom_selector

    Optional callable object as custom selector. When custom_selector is provided, path_regex and where must be None. The signature of custom_selector is:

    (key_path, value) -> should_select or (key_path, value, parent) -> should_select

Returns:

A dict of key path to value as results for selected values.