2

So i am trying to use a function that returns values, but i want these values to be returned into a different function. An example of something that i need is below.

def returner():
    x=1
    y=2
    z=3
    return x,y,z
def tester(arg1,arg2,arg3):
    print arg1,arg2,arg3

tester(returner())

What i would like it to do is print 1,2,3 however i have not been able to do it with this because it says "tester takes exactly 3 arguments, 1 given." Is there something i am missing or is this impossible?

IT Ninja
  • 6,174
  • 10
  • 42
  • 65

1 Answers1

12

You want to use * - the splat (or star) operator:

tester(*returner())

This is argument unpacking - it unpacks the tuple of returned values into the arguments for the function.

>>> def test():
...    return 1,2,3
... 
>>> def test2(arg1, arg2, arg3):
...    print(arg1, arg2, arg3)
... 
>>> test2(*test())
1 2 3
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Thank you very much! you will get your pts. soon :) – IT Ninja Apr 29 '12 at 22:23
  • This is a nice answer but the terminology is a bit off. Most folks call it the star-operator and the operation is called argument unpacking. It helps to know the right terminology so you can search for it when needed. FYI, here is a link to the docs: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists – Raymond Hettinger Apr 29 '12 at 22:26
  • 2
    @RaymondHettinger [Splat gets used as well](http://stackoverflow.com/questions/2322355/proper-name-for-python-operator). And I did say *it unpacks the tuple of returned values into the arguments*, which is 'argument unpacking' with a bit more explanation. Either way, I edited in for clarification. – Gareth Latty Apr 29 '12 at 22:30