return multiple values from scipy root finding / optimization function
<p>I'm trying to return multiple values that are obtained inside a scipy root finding function (scipy.optimize.root).</p>

<p>For example:</p>

<pre><code>B = 1
def testfun(x, B):
    B = x + 7
    return B**2 + 9/18 - x

y = scipy.optimize.root(testfun, 7, (B))
</code></pre>

<p>Is there any way to return the value of B without using globals? </p>

<p>I'm not aware of anything SciPy specific, but how about a simple closure:</p>

<pre><code>from scipy import optimize

def testfun_factory():
    params = {}
    def testfun(x, B):
        params['B'] = x + 7
        return params['B']**2 + 9/18 - x
    return params, testfun

params, testfun = testfun_factory()
y = optimize.root(testfun, 7, 1)
print(params['B'])
</code></pre>

<p>Alternatively, an instance of a class with <a href="https://docs.python.org/3/reference/datamodel.html#object.__call__" rel="nofollow"><code>__call__</code></a> could also be passed as the callable.</p>

python function optimization scipy