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'
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