I am writing code with multiple functions where most of the functions include the same variables. I have provided some example functions below.
# First sample function
def cg2RollAxisHeight(z_frc, z_rrc, l_w, x_cg, z_cg):
theta = np.arctan((z_rrc-z_frc)/l_w)
z_axis = np.tan(theta)*l_w*x_cg
return z_cg-(z_axis + z_frc)
# Second Sample function
def FrontLateralWT(W, l_w, t_f, K_phiF, K_phiR, A_Y, z_frc, z_rrc, x_cg, z_cg):
H = CG.cg2RollAxisHeight(z_frc, z_rrc, l_w, x_cg, z_cg)
b = l_w-(l_w*x_cg)
return A_Y*W/t_f*(H*K_phiF/(K_phiF+K_phiR)+b/l_w*z_frc)
I would like to be able to define all variables and variable names in a single object (e.g. a dictionary) and be able to have my functions pull the required variables needed from that object.
I have tried using **kwargs in the following manner:
def cg2RollAxisHeight(**kwargs):
theta = np.arctan((z_rrc-z_frc)/l_w)
z_axis = np.tan(theta)*l_w*x_cg
return z_cg-(z_axis + z_frc)
kwargs = {'W': 180, 'l_w': 2.4, 't_f': 1540, 'K_phiF': 78000, 'K_phiR': 46000,
'A_Y': 2.5, 'z_frc': 25, 'z_rrc': 60, 'x_cg': .6, 'z_cg': .4}
test = cg2RollAxisHeight(**kwargs)
print(test)
The issue here is that the function does not recognize the key as the variable name. Is there a way to use the dictionary key as the variable name within the function? Or is there a better way to do what I am after? I want to avoid using a list because the function would be nearly impossible to decipher.
def cg2RollAxisHeight(params):
theta = np.arctan((params[7]-params[6])/params[1])
z_axis = np.tan(theta)*params[1]*params[9]
return paramms[10]-(z_axis + params[6])
params = [180, 2.4, 1540, 78000, 46000, 2.5, 25, 60, 0.6, 0.4}
test = cg2RollAxisHeight(params)
print(test)
While the above solution does work, it isn't a neat solution and I would have to do the same to many other much larger functions. Not ideal! Is there a way to create a single object that can be passed to multiple functions without editing the main body of the function?