Python callback variable scope
<p>I have a function <code>fun()</code> that binds a callback <code>callback()</code> when a matplotlib figure is clicked. I want this callback to be able to access the variable space of <code>fun()</code> to make changes. How can I go about this?</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

def callback(event):
    data = event.xdata

def fun():
    data = 0

    fig, ax = plt.subplots()
    ax.plot(np.random.rand(12), np.random.rand(12), 'go')
    fig.canvas.mpl_connect('button_release_event', callback)

    plt.show()
    return data

print fun()
</code></pre>

<p>Putting <code>data</code> in the <code>global</code> scope is not an acceptable solution. The function should be self-contained. The answer <a href="https://stackoverflow.com/questions/24960910/how-can-i-pass-parameters-to-on-key-in-fig-canvas-mpl-connectkey-press-event">here</a> would allow me to pass variables to <code>callback()</code>, but would not let me edit them.</p>

<p>I understand you would like to have some state, that can be changed during runtime. One option might be to use a callable object, that is not a function (I have not tested it):</p>

<pre><code>class Callback(object):
     def __init__(self, data):
         self.data = data
     def __call__(self, event):
         # Manipulate the data
         self.data += 1
...
datacallback = Callback(0)
fig.canvas.mpl_connect('button_release_event', datacallback)
print datacallback.data
</code></pre>

<p>That way we would have a counter how often the event is raised. But it works with any kind of data, also more complex than an integer.</p>

python matplotlib scope