Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking arguments: only named arguments may follow *expression

The following works beautifully in Python:

def f(x,y,z): return [x,y,z]  a=[1,2]  f(3,*a) 

The elements of a get unpacked as if you had called it like f(3,1,2) and it returns [3,1,2]. Wonderful!

But I can't unpack the elements of a into the first two arguments:

f(*a,3) 

Instead of calling that like f(1,2,3), I get "SyntaxError: only named arguments may follow *expression".

I'm just wondering why it has to be that way and if there's any clever trick I might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables.

like image 210
dreeves Avatar asked Oct 04 '12 04:10

dreeves


1 Answers

As Raymond Hettinger's answer points out, this may change has changed in Python 3 and here is a related proposal, which has been accepted. Especially related to the current question, here's one of the possible changes to that proposal that was discussed:

Only allow a starred expression as the last item in the exprlist. This would simplify the unpacking code a bit and allow for the starred expression to be assigned an iterator. This behavior was rejected because it would be too surprising.

So there are implementation reasons for the restriction with unpacking function arguments but it is indeed a little surprising!

In the meantime, here's the workaround I was looking for, kind of obvious in retrospect:

f(*(a+[3])) 
like image 72
dreeves Avatar answered Sep 21 '22 08:09

dreeves