The glom scope is a dictionary of extra values passed to the top-level glom call. These values can be accessed within the spec using the S object, which supports attribute-style dot-access for its keys.
Basic Usage
Pass a scope dictionary to glom and access its keys via S.
from glom import glom, T, S
count_spec = T.count(S.search)
glom(['a', 'c', 'a', 'b'], count_spec, scope={'search': 'a'})
# Output: 2
Updating the scope with S() and A
Scopes are dynamic. You can save values from the target into the scope using S or A:
S(key=spec): Evaluates spec and saves the result to key in the scope.A.key: A shorthand to assign the current target to key in the scope.
from glom import glom, S, A
target = {'data': {'val': 9}}
# Saving target value to scope
spec = (S(value=T['data']['val']), {'val': S['value']})
glom(target, spec)
# Output: {'val': 9}
# Using A as a shortcut for the current target
spec_alt = ('data.val', A.value, {'val': S.value})
glom(target, spec_alt)
# Output: {'val': 9}
Persistent state with Vars and S.globals
By default, changes to the scope are local to the current spec. To persist state across different parts of a spec, use a Vars object.
S.globals: A pre-created Vars object available throughout the entire glom call.Vars: A mutable namespace that allows child scopes to store state that persists beyond their local scope.
from glom import glom, A, S
# Using S.globals to persist a value
last_spec = ([A.globals.last], S.globals.last)
glom([3, 1, 4, 1, 5], last_spec)
# Output: 5