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 file
Parameters are defined in a TOML file named params.toml
.
[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 params
.
import toml
pfile = 'params.toml'
with open(pfile, 'r') as f:
params = toml.load(f)
Example 1
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)
Example 2
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)
calc_feedx(**params)
. It shortens code a lot, but violates PEP 20's "Explicit is better than implicit.". I think all three are reasonable options. \$\endgroup\$calc_feedx(d, rho, temp)
are onlyd
,rho
, andtemp
. Using**params
causes an error because the dictionary contains more parameters than what the function uses. \$\endgroup\$