I'm new to Python and have a problem-specific question about how to access non-returned variables defined within a function.
I am using an analysis package in Python that requires a user-defined function as input. It expects a function defined in a particular way that returns a single output. However, for diagnostic purposes, I would like to obtain multiple outputs from this function after it is called (e.g. to produce diagnostic plots at a particular stage of the analysis). However, I can't modify the function to return multiple outputs (unless I modify every instance of it being called by the analysis code--not practical); this would result in an error.
For instance, in the following example,the user defined function returns f1+f2, but for diagnostic purposes, say I would like to know what f1 and f2 are individually:
def my2dfunction(x,y,theta):
'''x and y are 1-d arrays of len(x)==len(y)
theta is an array of 5 model parameters '''
f1=theta[0]+theta[1]*x+theta[2]*x**2
f2=theta[3]*y+theta[4]*y**2
return f1+f2
Researching on this site I've come up with 2 possible solutions:
Create a global variable containing the values for f1 and f2 from the latest function call, which I can access at any time:
live_diagnostic_info={'f1':0, 'f2':0} def my2dfunction(x,y,theta): f1=theta[0]+theta[1]*x+theta[2]*x**2 f2=theta[3]*y+theta[4]*y**2 global live_diagnostic_info={'f1':f1, 'f2':f2} return f1+f2
Define a second function identical to the first with multiple return values to call in only the instances where I need diagnostic information.
def my2dfunction_extra(x,y,theta): f1=theta[0]+theta[1]*x+theta[2]*x**2 f2=theta[3]*y+theta[4]*y**2 return f1+f2,f1,f2
I think both would work for my purposes, but I'm wondering if there is another way to pass non-returned variables from a function in Python. (e.g. I do a lot of coding in IDL, where extra information can be passed through keywords, without modifying the return statement, and wonder what the Python equivalent would be if it exists).