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

Nick Craig-Wood nick at craig-wood.com
Fri May 23 05:30:09 EDT 2008


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.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list