call f(a, *b) with f(*a, **b) ?

inhahe inhahe at gmail.com
Fri May 23 06:12:25 EDT 2008


"Nick Craig-Wood" <nick at craig-wood.com> wrote in message 
news:slrng3d2g4.3re.nick at irishsea.home.craig-wood.com...
> bukzor <workitharder at gmail.com> wrote:
>>  That does, in fact work. Thanks! I'm a little sad that there's no
>>  builtin way to do it, owell.
>>
>> >>> def f(a, *args):
>>  ...     print a
>>  ...     for b in args: print b
>>  ...
>> >>> import inspect
>> >>> a = [2,3]
>> >>> b = {'a':1}
>> >>> inspect.getargspec(f)
>>  (['a'], 'args', None, None)
>> >>> map(b.get, inspect.getargspec(f)[0])
>>  [1]
>> >>> map(b.get, inspect.getargspec(f)[0]) + a
>>  [1, 2, 3]
>> >>> f(*map(b.get, inspect.getargspec(f)[0]) + a)
>>  1
>>  2
>>  3
>
> If I saw that in my code I'd be wanting to get rid of it as soon as
> possible!
>
> I'd re-write f() to have all named arguments then the problem becomes
> easy and the answer pythonic (simple dictionary manipulation)...
>
> So instead of f(a, *args) have f(a, list_of_args).
>
> The f(*args) syntax is tempting to use for a function which takes a
> variable number of arguments, but I usually find myself re-writing it
> to take a list because of exactly these sort of problems.  In fact I'd
> be as bold to say that f(*args) is slightly un-pythonic and you should
> avoid as a user interface.  It does have its uses when writing
> polymorphic code though.
>


(I second that) the function should definitely be changed if possible.  it's 
hard to say what the real constraints of the problem are, so I just answered 
his question as if that's what he actually needed (assuming the length of 
the list and number of named arguments would be variable).

if we assume the constraints are that:
1.he has list, l
2.he has a dictionary, d
3.he wants the function to print the values in the dictionary according to a 
specific order of their keys as defined by the function, followed by the 
values of the list
then:

def f(d, l):
  order_of_keys = ['a']
  for key in order_of_keys:
    print d[key]
  for element in l:
    print element

#not tested






More information about the Python-list mailing list