iterobj#
- class iterobj(obj, func, inplace=False, twigs_only=False, verbose=False, _trace=None, _output=None, *args, **kwargs)[source]#
Iterate over an object and apply a function to each twig.
Can modify an object in-place, or return a value. See also
sc.search()
for a function to search through complex objects.- Parameters:
obj (any) – the object to iterate over
func (function) – the function to apply
inplace (bool) – whether to modify the object in place (else, collate the output of the functions)
twigs_only (bool) – whether to apply the function only to twigs of the object
verbose (bool) – whether to print progress.
_trace (list) – used internally for recursion
_output (list) – used internally for recursion
*args (list) – passed to func()
**kwargs (dict) – passed to func()
Examples:
data = dict(a=dict(x=[1,2,3], y=[4,5,6]), b=dict(foo='string', bar='other_string')) # Search through an object def check_type(obj, which): return isinstance(obj, which) out = sc.iterobj(data, check_type, which=int) print(out) # Modify in place -- collapse mutliple short lines into one def collapse(obj): string = str(obj) if len(string) < 10: return string else: return obj sc.printjson(data) sc.iterobj(data, collapse, inplace=True) sc.printjson(data)
New in version 3.0.0.