Unpacking sequences and keywords in one function call

Steve Holden steve at holdenweb.com
Tue Nov 14 03:43:01 CET 2006


Noah Rawlins wrote:
> ram wrote:
>> Stupid question #983098403:
>>
>> I can't seem to pass an unpacked sequence and keyword arguments to a
>> function at the same time. What am I doing wrong?
>>
>> def f(*args, **kw):
>>     for a in args:
>>         print 'arg:', a
>>     for (k,v) in kw.iteritems():
>>         print k, '=', v
>>
>>>>> f(1,2)
>> arg: 1
>> arg: 2
>>
>>>>> f(*[1,2])
>> arg: 1
>> arg: 2
>>
>>>>> f(1,2, a=1)
>> arg: 1
>> arg: 2
>> a = 1
>>
>>>>> f(*[1,2], a=1)
>>     File "<stdin>", line 1
>>       f(*[1,2], a=1)
>>                   ^
>>     SyntaxError: invalid syntax 
>>
>> Thanks,
>> Rick
>>
> 
> I don't know if it's because there's some potential ambiguity (that I'm 
> not seeing), but yeah, you just can't do that.  This should work though...
> 
>  >>> f(*[1, 2], **{'a':1})
> 
> noah

You should be ok as long as you use the following ordering of actual 
arguments in a function call:

   1. Positional arguments
   2. Keyword arguments
   3. * sequence
   4. ** dict

In other words try (untested):

   f(a=1, *[1, 2])

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list