class IterObj(obj, func=None, inplace=False, copy=False, leaf=False, atomic='default', verbose=False, _trace=None, _output=None, 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:

custom_type (func): a custom function for returning a string for a specific object type (should return ‘’ 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


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)
New in version 3.1.2.


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

Print, with output indented successively


Return an iterator over items in this object


Get the value for the item

setitem(key, value)[source]#

Set the value for the item


Shortcut to check_iter_type()


Actually perform the iteration over the object