Asher11
Asher11

Reputation: 1335

pass multiple parameters to function in multiple tuple sets - python

essentially I have a function which I need to pass to a bunch of values in two different moments (here skipped for practical reasons), hence, I thought need to split all the parameters in two tuple sets after which I'd pass the first set and then the second thinking - mistakenly - that python would allocate all the available n parameters of the function to the values passed with the tuple and then the rest with the second tuple. That is not the case:

def example_F_2(x, y, z, g):
    return x * y + z * g

e = (1,2)
r = (3,4)
print(example_F_2(e, r))

in fact:

Traceback (most recent call last):
  File "C:/Users/francesco/PycharmProjects/fund-analysis/test_sheet.py", line 7, in <module>
    print(example_F_2(e, r))
TypeError: example_F_2() missing 2 required positional arguments: 'z' and 'g'

what can I do? I am guessing something from this page should work (https://docs.python.org/3.5/library/functools.html) but I have been unable to do it myself

Upvotes: 0

Views: 1416

Answers (2)

Dan
Dan

Reputation: 1227

Perhaps you can use something like this:

def example_F_2(e=None, r=None):
    first_term = 0
    second_term = 0
    if e is not None:
        first_term = e[0] * e[1]
    if r is not None:
        second_term = r[0] * r[1]
    return first_term + second_term


e = (1, 2)
r = (3, 4)
print example_F_2(e, r)
> 14
print example_F_2(e=e)
> 2
print example_F_2(r=r)
> 12

Upvotes: 0

mhawke
mhawke

Reputation: 87134

A very simple way is to concatenate the tuples and then unpack them as you pass them to your function:

print(example_F_2(*(e+r)))

Upvotes: 2

Related Questions