Salai V V
Salai V V

Reputation: 15

Can I write python code that modifies itself during execution?

I mean,

target_ZCR_mean = sample_dataframe_summary['ZCR'][1]
target_ZCR_std = sample_dataframe_summary['ZCR'][2]
lower_ZCR_lim = target_ZCR_mean - target_ZCR_std
upper_ZCR_lim = target_ZCR_mean + target_ZCR_std

target_RMS_mean = sample_dataframe_summary['RMS'][1]
target_RMS_std = sample_dataframe_summary['RMS'][2]
lower_RMS_lim = target_RMS_mean - target_RMS_std
upper_RMS_lim = target_RMS_mean + target_RMS_std

target_TEMPO_mean = sample_dataframe_summary['Tempo'][1]
target_TEMPO_std = sample_dataframe_summary['Tempo'][2]
lower_TEMPO_lim = target_TEMPO_mean - target_TEMPO_std
upper_TEMPO_lim = target_TEMPO_mean + target_TEMPO_std

target_BEAT_SPACING_mean = sample_dataframe_summary['Beat Spacing'][1]
target_BEAT_SPACING_std = sample_dataframe_summary['Beat Spacing'][2]
lower_BEAT_SPACING_lim = target_BEAT_SPACING_mean - target_BEAT_SPACING_std
upper_BEAT_SPACING_lim = target_BEAT_SPACING_mean + target_BEAT_SPACING_std

each block of four lines of code are very similar to each other except for a few characters.

Can I write a function, a class or some other piece of code, such that I can wrap just a template of four lines of code into it and let it modify itself during runtime to get the code do the work of the above code...?

By the way, I use python 3.6.

Upvotes: 0

Views: 816

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12157

If you find yourself storing lots of variables like this, especially if they are related, there is almost certainly a better way of doing it. Modifying the source dynamically is never the solution. One way is to use a function to keep the repeated logic, and use a namedtuple to store the resultant data:

import collections
Data = collections.namedtuple('Data', 'mean, std, lower_lim, upper_lim')

def get_data(key, sample_dataframe_summary):
     mean = sample_dataframe_summary[key][1]
     std = sample_dataframe_summary[key][2]
     lower_lim = mean - std
     upper_lim = mean + std
     return Data(mean, std, lower_lim, upper_lim)

zcr = get_data('ZCR', sample_dataframe_summary)
rms = get_data('RMS', sample_dataframe_summary)
tempo = get_data('Tempo', sample_dataframe_summary)
beat_spacing = get_data('Beat Spacing', sample_dataframe_summary)

then you can access the data with the . notation like zcr.mean and tempo.upper_lim

Upvotes: 4

Related Questions