Importing an output from another function

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

```On 17 Mar 2006 12:15:28 -0800
"Byte" <eoinrogers at gmail.com> 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
informative):

"""
import random

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

def Func2():
print output

Func1()
Func2()
"""

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

Func2(Func1())
"""

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)

or

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

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.

Cheers,
Terry

--
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com

```