2

I have a function which goes something like this:

def do_something(lis):
    do something
    return lis[0], lis[1]

and another function which needs to take those two return objects as arguments:

def other_function(arg1, arg2):
    pass

I have tried:

other_function(do_something(lis))

but incurred this error:

TypeError: other_function() missing 1 required positional argument: 'arg2'

1
  • 1
    show other_function function declaration Commented Oct 6, 2016 at 12:57

2 Answers 2

3

You need to unpack those arguments when calling other_function.

other_function(*do_something(lis))

Based on the error message, it looks like your other function is defined (and should be defined as)

def other_function(arg1, arg2):
    pass

So, when you return from do_something, you are actually returning a tuple containing (lis[0], lis[1]). So when you originally called other_function, you passing a single tuple, when your other_function was still expecting a second argument.

You can see this if you break it down a bit further. Below is a breakdown of how the returns look like when handled differently, a reproduction of your error and a demo of the solution:

Returning in to a single variable will return a tuple of the result:

>>> def foo():
...     lis = range(10)
...     return lis[1], lis[2]
...
>>> result = foo()
>>> result
(1, 2)

Returning in to two variables, unpacks in to each var:

>>> res1, res2 = foo()
>>> res1
1
>>> res2
2

Trying to call other_function with result which now only holds a tuple of your result:

>>> def other_function(arg1, arg2):
...     print(arg1, arg2)
...
>>> other_function(result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: other_function() missing 1 required positional argument: 'arg2'

Calling other_function with res1, res2 that holds each value of the return from foo:

>>> other_function(res1, res2)
1 2

Using result (your tuple result) and unpacking in your function call to other_function:

>>> other_function(*result)
1 2
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like this:

other_function(*do_something(list))

The * char will expand the tuple returned by do_something.

Your do_something function is actually returning a tuple which contains several values but is only one value itself.

See the doc for more details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.