# Python: Getting second output variable from minimizing a computationally intensive function on first outputs

I have a function in python that is quite computationally expensive to evaluate, of the form:

def f(x, args):
...
return y_1, y_2  # where y_1 is scalar, and y_2 can
# be a vector of other results


I need to minimize y_1 with respect to x, and I have a quite good initial guess for x, such that the minimizer does not take a lot of iterations in general. I wrap the function for the purpose:

def g(x, args):
return f(x,args)[0]


I'm interested in both the optimal x, and the values of the function y_1 and y_2 at this x, since I need them later on. Computing y_1 and y_2 requires several multidimensional interpolations of the same functions, which is why the function takes a while to compute. However, computing y_2 given those interpolations (which again, are the same for y_1) is quite quick.

I can easily recompute y_2 given x_opt by running f(x_opt,args)[1], but that is costly. I was wondering if there is a way to get y_2 directly as an output from the minimization process, once the minimizer has found the optimal x.

Have you considered defining y_2 as a global variable so that it can be referenced by other functions after f(x)? From the sounds of your question, you're just trying to reference y_2 after initial calculation, no?