IterObj#

class IterObj(obj, func=None, inplace=False, copy=False, leaf=False, recursion=0, depthfirst=True, atomic='default', skip=None, rootkey='root', verbose=False, iterate=True, custom_type=None, custom_iter=None, custom_get=None, custom_set=None, *args, **kwargs)[source]#

Bases: object

Object iteration manager

For arguments and usage documentation, see sc.iterobj(). Use this class only if you want more control over how the object is iterated over.

Class-specific args:

iterate (bool): whether to do iteration upon object creation custom_type (func): a custom function for returning a string for a specific object type (should return None by default) custom_iter (func): a custom function for iterating (returning a list of keys) over an object custom_get (func): a custom function for getting an item from an object custom_set (func): a custom function for setting an item in an object

Example:

import sciris as sc

# Create a simple class for storing data
class DataObj(sc.prettyobj):
    def __init__(self, **kwargs):
        self.keys   = tuple(kwargs.keys())
        self.values = tuple(kwargs.values())

# Create the data
obj1 = DataObj(a=[1,2,3], b=[4,5,6])
obj2 = DataObj(c=[7,8,9], d=[10])
obj = DataObj(obj1=obj1, obj2=obj2)

# Define custom methods for iterating over tuples and the DataObj
def custom_iter(obj):
    if isinstance(obj, tuple):
        return enumerate(obj)
    if isinstance(obj, DataObj):
        return [(k,v) for k,v in zip(obj.keys, obj.values)]

# Define custom method for getting data from each
def custom_get(obj, key):
    if isinstance(obj, tuple):
        return obj[key]
    elif isinstance(obj, DataObj):
        return obj.values[obj.keys.index(key)]

# Gather all data into one list
all_data = []
def gather_data(obj, all_data=all_data):
    if isinstance(obj, list):
        all_data += obj

# Run the iteration
io = sc.IterObj(obj, func=gather_data, custom_type=(tuple, DataObj), custom_iter=custom_iter, custom_get=custom_get)
print(all_data)
New in version 3.1.2.
New in version 3.1.5: “norecurse” argument; better handling of atomic classes
New in version 3.1.6: “depthfirst” argument; replace recursion with a queue; “to_df()” method

Methods

indent(string='', space='  ')[source]#

Print, with output indented successively

iteritems(parent, trace)[source]#

Return an iterator over items in this object

getitem(key, parent)[source]#

Get the value for the item

setitem(key, value, parent)[source]#

Set the value for the item

check_iter_type(obj)[source]#

Shortcut to check_iter_type()

check_proceed(subobj, newid)[source]#

Check if we should continue or not

process_obj(parent, trace, key, subobj, newid)[source]#

Process a single object

iterate()[source]#

Actually perform the iteration over the object

flatten_traces(sep='_')[source]#

Convert trace tuples to strings for easier reading

to_df()[source]#

Convert the output dictionary to a dataframe