Is it possible to access a local variable in another function?
<p>Goal: Need to use local variable in another function. Is that possible in Python?</p>

<p>I would like to use the local variable in some other function. Because in my case I need to use a counter to see the number of connections happening and number of connections releasing/ For that I am maintaining a counter. To implement that I have written sample code for count and returning local variable in another function.</p>

<p>How can I print <code>t</code> &amp; <code>my_reply</code> in the <code>test()</code> function?</p>

<p>Code: counter_glob.py</p>

<pre><code>my_test = 0
t = 0

def test():
    print("I: ",t)
    print("IIIIIIII: ",my_reply)

def my():
    global t
    reply = foo()
    t = reply
    print("reply:",reply)
    print("ttttt:",t)

def foo():
    global my_test
    my_test1 = 0
    my_test += 1
    print my_test1
    my_test1 = my_test
    my_test += 1
    print("my_test:",my_test1)
    return my_test1

my()
</code></pre>

<p>Result:</p>

<pre class="lang-none prettyprint-override"><code>&gt; $ python counter_glob.py
 0
 ('my_test:', 1)
 ('reply:', 1)
 ('ttttt:', 1)
</code></pre>

<p>Except <code>closure</code> you wont have access to local vars outside the scope of your functions.
If variables have to be shared across different methods better make them as global as @pavnik has mentioned.</p>

python python-2.7 python-3.x