[IPython-user] Using variables created in script

Carlos Córdoba ccordoba12@gmail....
Sat Mar 20 21:06:54 CDT 2010


You can also use the global keyword to export the variables inside a
function into the global namespace.

For example if you define:

def f(x):
    global a
    a=5
    return x+a

you can check the value of a outside of f.

Hope this helps,
Carlos

2010/3/18 Scott Sinclair <scott.sinclair.za@gmail.com>

> >On 18 March 2010 22:18, lixo1 <lixo1@hotmail.fr> wrote:
> > Yes if you uses %run it loads a function but I really would like to get
> > something like matlab, for example in Matlab I create a function like
> this:
> >
> > function [result,dataA,dataB] = Toff(x);
> >  stuff
> >  resuts = 65;
> >  ...
> >
> > It means that when I call this function the variables result, dataA,
> dataB
> > are created and stocked in the workspace. If I well understand in ipython
> > (python) it's like C, you return 1 singular value from a function.
>
> Python does return a single object, but you can pack your variables
> into a tuple object and return that.
>
> Something like this:
>
> # example.py
> import numpy as np
>
> def foo():
>    a = np.ones(3)
>    b = 3*a
>    c = a+b
>
>    return a, b, c
>
> A, B, C = foo()
>
> IPython session:
>
> [~] |1>dir()
>   <1>
> ['In',
>  'LA',
>  'Out',
>  '_',
>  '__',
>  '__IP',
>  '___',
>  '__builtins__',
>  '__name__',
>  '__package__',
>  '_dh',
>  '_i',
>  '_i1',
>  '_ih',
>  '_ii',
>  '_iii',
>  '_ip',
>  '_oh',
>  '_prompt_title',
>  '_sh',
>  'help',
>  'os',
>  'path',
>  'up']
> [~] |2>%run example.py
> [~] |3>dir()
>   <3>
> ['A',
>  'B',
>  'C',
>  'In',
>  'LA',
>  'Out',
>  '_',
>  '_1',
>  '__',
>  '__IP',
>  '___',
>  '__builtins__',
>  '__file__',
>  '__name__',
>  '__nonzero__',
>  '__package__',
>  '_dh',
>  '_i',
>  '_i1',
>  '_i2',
>  '_i3',
>  '_ih',
>  '_ii',
>  '_iii',
>  '_ip',
>  '_oh',
>  '_prompt_title',
>  '_sh',
>  'foo',
>  'help',
>  'np',
>  'os',
>  'path',
>  'up']
> [~] |4>A
>   <4> array([ 1.,  1.,  1.])
> [~] |5>B
>   <5> array([ 3.,  3.,  3.])
> [~] |6>C
>   <6> array([ 4.,  4.,  4.])
>
> Cheers,
> Scott
> _______________________________________________
> IPython-user mailing list
> IPython-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/ipython-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/ipython-user/attachments/20100320/9eace524/attachment.html 


More information about the IPython-user mailing list