3
votes

I'm passing a lot data around; specifically, I'm trying to pass the output of a function into a class and the output contains a tuple with three variables. I can't directly pass the output from my function (the tuple) into the class as in the input parameters.

How can format the tuple so it is accepted by the class without input_tuple[0], input_tuple[1], input_tuple[2]?

Here is a simple example:

#!/usr/bin/python

class InputStuff(object):

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c


input_tuple = (1, 2, 3)
instance_1 = InputStuff(input_tuple)

# Traceback (most recent call last):
#   File "Untitled 3.py", line 7, in <module>
#     instance_1 = InputStuff(input_tuple)
# TypeError: __init__() takes exactly 4 arguments (2 given)

InputStuff(1, 2, 3)
# This works
2
instance_1 = InputStuff(*input_tuple) - see stackoverflow.com/q/36901/3001761 - jonrsharpe
that worked, can you put that as an answer so i can mark it correct? - O.rka
I've told you what the duplicate is - I'd close it, but I've run out of votes! (Thanks @BhargavRao) - jonrsharpe
@Jonrsharpe I see that it may be a duplicate but if someone doesn't know about the * operator or that unpacking an argument list with * is a possibility then they won't search that to find the answer. I think the wording of the title is very straight forward in a search. - O.rka
You mean like stackoverflow.com/q/1993727/3001761, stackoverflow.com/q/10625220/3001761, ...? How many different versions do you think we need? - jonrsharpe

2 Answers

5
votes

You can use the * operator to unpack the argument list:

input_tuple = (1,2,3)
instance_1 = InputStuff(*input_tuple)
2
votes

You are looking for: Unpacking Argument Lists

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]