Importing an output from another function

Terry Hancock hancock at
Sat Mar 18 03:01:37 CET 2006

On 17 Mar 2006 12:15:28 -0800
"Byte" <eoinrogers at> wrote:
> Probably a stupid question, but I'm a newbie and this
> really pisses me off. Run this script:
> import random
> def Func1():
>     choice = ('A', 'B', 'C')
>     output = random.choice(choice)
> def Func2():
>     print output
> Func1()
> Func2()

Several possible solutions. The simplest (but least

import random

def Func1():
    global output
    choice = ('A', 'B', 'C')
    output = random.choice(choice)

def Func2():
    print output


i.e. make output a global variable

But as has already been pointed out, you aren't really using
the nature of functions here.  Better:

import random

def Func1():
    return random.choice(('A', 'B', 'C'))

def Func2(output):
    print output


You later ask about returning multiple values. Python is
pretty cool in this respect -- you can return multiple
values in a tuple, which can then be "unpacked"
automatically. This gives you a nice many-to-many idiom for
function calls, e.g.:

x, y = random_point(x_min, x_max, y_min, y_max)

And if you need to pass that to a function which takes two
arguments (x,y), you can:

set_point(*random_point(x_min, x_max, y_min, y_max))

Of course, some people would rather see that expanded out, 
and indeed, too many nested function calls can be hard on
the eyes, so you might want to do this anyway:

x, y = random_point(x_min, x_max, y_min, y_max)
set_point(x, y)


P = random_point(x_min, x_max, y_min, y_max)

and of course, it's possible that the function requires the
arguments in a different order, e.g.:

x, y = random_point(1,80,1,25)
set_rowcol(y, x, 'A')

or some such thing.

By far the coolest thing about tuple-unpacking, though, is
that this works like you'd expect it to:

x, y = y, x

instead of being a dumb mistake like this is:

x = y
y = x

which of course should be

temp = y
x = y
y = temp

But ewww that's ugly.


Terry Hancock (hancock at
Anansi Spaceworks

More information about the Python-list mailing list