In my Python projects, I often define parameters in a TOML, YAML, or JSON file. Those parameters are loaded into a dictionary which is utilized by various functions in the project. See below for some examples. I'm curious on how others would approach this and if there are better ways to work with functions and parameter files.
Parameters are defined in a TOML file named
[feedstock] d = 0.8 phi = [ 0.65, 0.8, 0.95 ] k = 1.4 cp = 1800 temp = 60 ei = 1.2 eo = 1.8 rho = 540 [reactor] d = 5.4 h = 8.02 temp = 500 p = 101325
The parameters are loaded into a dictionary named
import toml pfile = 'params.toml' with open(pfile, 'r') as f: params = toml.load(f)
This example explicitly defines each input variable to the function. I like this example because it is obvious on what the inputs are to the function. Values from the parameters dictionary are assigned to variables which are used as inputs to the function.
def calc_feedx(d, rho, temp): a = (1 / 4) * 3.14 * (d**2) x = a * rho * temp return x d = params['feedstock']['d'] rho = params['feedstock']['rho'] temp = params['feedstock']['temp'] x = calc_feedx(d, rho, temp)
This example only has one input variable to the function which is a dictionary that contains all the parameters utilized by the function. I don't like this approach because it's not obvious what the input parameters are for the function. This example provides the entire dictionary to the function which accesses the parameters from within the function. Not all the parameters defined in the dictionary are used by the function.
def calc_feedx(params): d = params['feedstock']['d'] rho = params['feedstock']['rho'] temp = params['feedstock']['temp'] a = (1 / 4) * 3.14 * (d**2) x = a * rho * temp return x x = calc_feedx(params)