[IPython-user] Using variables created in script

Scott Sinclair scott.sinclair.za@gmail....
Thu Mar 18 23:57:07 CDT 2010


>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


More information about the IPython-user mailing list