I have n numpy arrays which all contain time series data for t periods. It is not an option to instead have one nxt matrix. I am storing all these arrays in a ResultSimulation object.

I seem to have repetitive code, which I am wondering how to shorten.

It starts with

ResultSimulation.v0 = ResultSteadyState.v0[::-1].copy()
ResultSimulation.v1 = ResultSteadyState.v1[::-1].copy()
ResultSimulation.nl = ResultSteadyState.nl[::-1].copy()
ResultSimulation.nh = ResultSteadyState.nh[::-1].copy()
ResultSimulation.ul = ResultSteadyState.ul[::-1].copy()
ResultSimulation.uh = ResultSteadyState.uh[::-1].copy()
ResultSimulation.V1 = ResultSteadyState.V1[::-1].copy()

at some place there is

# nTSteady is some number
ResultSimulation.v0 = ResultSimulation.v0[:nTSteady]
ResultSimulation.v1 = ResultSimulation.v1[:nTSteady]
ResultSimulation.nl = ResultSimulation.nl[:nTSteady]
ResultSimulation.nh = ResultSimulation.nh[:nTSteady]
ResultSimulation.ul = ResultSimulation.ul[:nTSteady]
ResultSimulation.uh = ResultSimulation.uh[:nTSteady]
ResultSimulation.V1 = ResultSimulation.V1[:nTSteady]

and finally,

addZeros = np.zeros((additionalSize,))
ResultSimulation.v0 = np.concatenate((ResultSimulation.v0, addZeros))
ResultSimulation.v1 = np.concatenate((ResultSimulation.v1, addZeros))
ResultSimulation.nl = np.concatenate((ResultSimulation.nl, addZeros))
ResultSimulation.nh = np.concatenate((ResultSimulation.nh, addZeros))
ResultSimulation.ul = np.concatenate((ResultSimulation.ul, addZeros))
ResultSimulation.uh = np.concatenate((ResultSimulation.uh, addZeros))

I guess one way to reduce this repetitive code, is to use "variable variable names", a practice that isn't encouraged in Python. Another alternative is to store them not directly in the object, but in an intermediate dict:

for series in ResultSimulation.myDict:
    ResultSimulation.myDict[series] = ResultSteadyState.myDict[series].copy()

for the first case. Say I don't like these two options+. What else can I do?

+: I dont mind creating an intermediate dictionary, but I want to keep my numpy arrays as properties of the object, and not stored in a dictionary within the object.


1 Answer 1


You can get the behavior you want using getattr and setattr, this should do the trick for your first example:

for attr in ('v0', 'v1', 'nl', 'nh', 'ul', 'uh', 'V1'):
    setattr(ResultSimulation, attr,
            getattr(ResultSimulation, attr)[::-1].copy)

It should be obvious how to modify the others to fit the same pattern.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.