Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially unpack parameters in python

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?

like image 758
sashkello Avatar asked Jul 04 '26 04:07

sashkello


1 Answers

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)).

like image 122
Burhan Khalid Avatar answered Jul 05 '26 18:07

Burhan Khalid