I know in Python we can unpack parameters from a tuple or list:
def add(x,y,z):
return x + y + z
xyz = (1,2,3)
s = add(*xyz)
But what is the proper way to accomplish something like this:
xy = (1,2)
s = add(*xy, 3)
SyntaxError: only named arguments may follow *expression
I can do this:
s = add(*xy + (3,))
but that looks ugly and badly readable, and if I have a few more variables in there it would be very messy.
So, is there a cleaner way to deal with such situation?
If you name your arguments; you can then proceed as you like:
>>> def foo(x=None,y=None,z=None):
... return x+y+z
...
>>> s = foo(*(1,2),z=3)
>>> s
6
Now if you do it like this, you can't override keyword arguments, so foo(*(1,2), y=3) will not work; but you can switch the order around as you like foo(z=3, *(1,2)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With