440,222 Members | 2,478 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

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

 P: n/a This question seems easy but I can't figure it out. Lets say there's a function: def f(a, *args): print a for b in args: print b and elsewhere in your program you have a list and a dict like this: args = [2, 3] kwargs = {'a':1} I'd like to get f() to print something like the following, but I can't figure out how. 1 2 Jun 27 '08 #1
5 Replies

 P: n/a "bukzor"

 P: n/a >1 >2 actually, you don't want it to print 3 also? if not, then you would do f(*map(kwargs.get, inspect.getargspec(f)[0])+args[:1]) import inspect f(*map(kwargs.get, inspect.getargspec(f)[0])+args) Jun 27 '08 #3

 P: n/a On May 22, 5:39*pm, "inhahe"

 P: n/a On May 22, 5:29*pm, "inhahe" >def f(a, *args): ... print a ... for b in args: print b ... >>import inspecta = [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 Jun 27 '08 #5

 P: n/a bukzor def f(a, *args): ... print a ... for b in args: print b ... >import inspecta = [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

This discussion thread is closed

Replies have been disabled for this discussion.