3

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • 4
    `instance_1 = InputStuff(*input_tuple)` - see http://stackoverflow.com/q/36901/3001761 – jonrsharpe Oct 01 '15 at 20:52
  • 1
    that worked, can you put that as an answer so i can mark it correct? – O.rka Oct 01 '15 at 20:54
  • 1
    I've told you what the duplicate is - I'd close it, but I've run out of votes! (Thanks @BhargavRao) – jonrsharpe Oct 01 '15 at 20:57
  • 1
    @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 Oct 01 '15 at 21:08
  • You mean like http://stackoverflow.com/q/1993727/3001761, http://stackoverflow.com/q/10625220/3001761, ...? How many different versions do you think we need? – jonrsharpe Oct 01 '15 at 21:10
  • @Jonrsharpe, those definitely explain it. I didn't see them when I was searching. Sorry about that. – O.rka Oct 01 '15 at 21:15

2 Answers2

9

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

input_tuple = (1,2,3)
instance_1 = InputStuff(*input_tuple)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

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]
xiº
  • 4,605
  • 3
  • 28
  • 39