Dynamically calling and assigning a variable from a config python files

Question:

I have a list of parameters in a config file, if a specific model file is called in my script I want to dynamically assign the appropriate parameters to the variable name

config file looks like this:

tune_model_selection = ['logreg_module', 'random_forest_module']

logreg_module_tune_parameter_grid = {
"C": [0.01, 0.1, 1.0, 1.5, 2.0, 5.0, 10.0],
"class_weight": ['balanced', None],
"penalty": ['l2'],
"solver": ['newton-cg', 'lbfgs', 'liblinear']
}


random_forest_module_tune_parameter_grid = {
"n_estimators" : [100, 300, 500, 800, 1200],
"max_depth" : [5, 8, 15, 25, 30],
"min_samples_split" : [2, 5, 10, 15, 100],
"min_samples_leaf" : [1, 2, 5, 10] 
}

snippet of python script

 class Tune:

def __init__(self,
             dataframe,
             text_column,
             target_column_name,
             date_column,
             config,
             model_file #logreg_module or random_forest_module
             ):
    if model_file in config.tune_model_selection:
        self.config = config
        self.text_column = text_column
        self.model_type = config.tune_model_type[model_file]
        self.model_module = importlib.import_module('modules.' + model_file) 
        
        #model file =  "logreg_module" or "random_forest_module"
        param_grid = model_file + '_tune_parameter_grid'
        self.parameter_grid = config.param_grid

For the variable self.parameter_grid, I want it to call config.random_forest_module_tune_parameter_grid dictionary or config.logreg_module_tune_parameter_grid

how it is scripted right now, it throws an error of no variable in config file named "param_grid"

I instead want it to read the name of param_grid from the previous variable and find the dictionary with associated parameters dynamically in the config file

Asked By: Arica Christensen

||

Answers:

This is what getattr is for. You can look up attributes using strings.

        self.parameter_grid = getattr(config, param_grid)
Answered By: Tim Roberts