How do I use multiple return values of a method as arguments for a new call method in Python?

Viewed 20

Suppose I have two methods, one returns three int or float. The other takes three int or float values. How do I directly pass the results of one as arguments for the other?

from typing import Union
def gimme_numbers() -> Union[float,int]:
    return 1, 3.2, 2
def print_numbers(a, b, c: Union[float, int]):
    print(a, "should be 1")
    print(b, "should be 3.2")
    print(c, "should be 2")
print_numbers(gimme_numbers())

The above breaks and returns TypeError: print_numbers() missing 2 required positional arguments: 'b' and 'c'. Running gimme_numbers() alone returns a tuple: (1, 3.2, 2). Is there a way to indicate that I want the returned tuple to be (not sure what the word is) "unpacked" or "unzipped"?

The following code does what I want, but the intermediate assignment seems… inelegant.

from typing import Union
def gimme_numbers() -> Union[float,int]:
    return 1, 3.2, 2
def print_numbers(a, b, c: Union[float, int]):
    print(a, "should be 1")
    print(b, "should be 3.2")
    print(c, "should be 2")
x, y, z = gimme_numbers()
print_numbers(x, y, z)
2 Answers

You need Python's explode operator:

print_numbers(*gimme_numbers())

I figured it out. I add an asterisk * in front of the thing to be unpacked. This code will work.

from typing import Union
def gimme_numbers() -> Union[float,int]:
    return 1, 3.2, 2
def print_numbers(a, b, c: Union[float, int]):
    print(a, "should be 1")
    print(b, "should be 3.2")
    print(c, "should be 2")
print_numbers(*gimme_numbers())
Related