[IPython-User] %run and global variables

Tom Bennett tom.bennett@mail.zyzhu....
Thu Nov 24 00:26:20 CST 2011


Hi,

So I have a simple test program - test.py:

a = b = 1
def test1():
    global a
    print "a=",a
    a = 2

def test2():
    global b
    print "b =", b
    b = 2

def test3():
    g = globals()
    g['b']=4


test1()
print "a=",a

--------------------------------------

If I run it in an ipython session, I get the following:

In [2]: run test
a= 1
a= 2
In [3]: test2()
b = 1
In [4]: b
Out[4]: 1
In [5]: test3()
In [6]: b
Out[6]: 1
In [7]: a
Out[7]: 2

What you can see is that if I run the function (test1) inside the script
test.py, it is able to change the global variable. If I run the function
(test2) under command prompt, it reads the value of the global variable all
right, but is not able to change the value. If I do it differently using
globals() as in test3(), I am still not able to change the global variable.


Now if I run it under ipython's namespace, using run - i, when I run
functions under command prompt, I am able to change global variables:

In [9]: run -i test
a= 1
a= 2
In [10]: test2()
b = 1
In [11]: b
Out[11]: 2

Why is that?

Thanks,
Tom
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/ipython-user/attachments/20111124/4d5e74ef/attachment.html 


More information about the IPython-User mailing list