Search code examples
pythonnumpyslicesetattr

Use built-in setattr simultaneously with index slicing


A class I am writing requires the use of variable-name attributes storing numpy arrays. I would like to assign values to slices of these arrays. I have been using setattr so that I can leave the attribute name to vary. My attempts to assign values to slices are these:

class Dummy(object):
        def __init__(self, varname):
        setattr(self, varname, np.zeros(5))

d = Dummy('x')
### The following two lines are incorrect
setattr(d, 'x[0:3]', [8,8,8])
setattr(d, 'x'[0:3], [8,8,8])

Neither of the above uses of setattr produce the behavior I want, which is for d.x to be a 5-element numpy array with entries [8,8,8,0,0]. Is it possible to do this with setattr?


Solution

  • Think about how you would normally write this bit of code:

    d.x[0:3] = [8, 8, 8]
    # an index operation is really a function call on the given object
    # eg. the following has the same effect as the above
    d.x.__setitem__(slice(0, 3, None), [8, 8, 8])
    

    Thus, to do the indexing operating you need to get the object refered to by the name x and then perform an indexing operation on it. eg.

    getattr(d, 'x')[0:3] = [8, 8, 8]