user1165419
user1165419

Reputation: 663

unpack return function arguments with *args

Looking for some guidance on how I can properly unpack return arguments in other functions using *args? This is the code;

 #!/usr/bin/python

def func1():

    test1 = 'hello'
    test2 = 'hey'

    return test1, test2


def func2(*args):

    print args[0]
    print args[1]

func2(func1)

The error message I'm getting;

    <function func1 at 0x7fde3229a938>
Traceback (most recent call last):
  File "args_test.py", line 19, in <module>
    func2(func1)
  File "args_test.py", line 17, in func2
    print args[1]
IndexError: tuple index out of range

I've tried a few things like args() but with no success. What am I doing wrong when trying to unpack?

Upvotes: 1

Views: 711

Answers (2)

Bahrom
Bahrom

Reputation: 4862

You didn't call func, so your func2 is actually getting a single argument, which is a function object. Change your code to: func2(*func1())

# While you're at it, also unpack the results so hello and hey are interpreted as 2 separate string arguments, and not a single tuple argument 
>>> func2(*func1())
hello
hey

>>> func2(func1)
<function func1 at 0x11548AF0>

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    func2(func1)
  File "<pyshell#19>", line 4, in func2
    print args[1]
IndexError: tuple index out of range

For reference:

>>> func1
<function func1 at 0x11548AF0>
>>> func1()
('hello', 'hey')
>>> 

Upvotes: 5

fulaphex
fulaphex

Reputation: 3219

func2 takes multiple arguments and you specified only one in your code
You can easily see if by printing all the args. You can also see, that it fails to print args[1] not args[0], because you have passed one argument to that function.

Upvotes: -1

Related Questions