Calling a function with unknown arguments?

Tombo thomas.dunham at
Thu Mar 8 00:48:26 CET 2007

On Mar 7, 10:55 pm, "Rob" <crow... at> wrote:
> I can get a list of a function's arguments.>>> def bob(a, b):
> ...     return a+b
> ...>>> bob.func_code.co_varnames
> ('a', 'b')
> Let's say that I also have a dictionary of possible arguments for this
> function.
> >>> possible = {'a':10, 'b':5, 'c':-3}
> How do I proceed to call bob(a=10, b=5) with this information?
> Thanks!

You can do this with a list comprehension:
bob(*[possible[k] for k in bob2.func_code.co_varnames])

The LC creates a list of arg values in the same order as the var names
for the function. Putting a * before the list when you call bob()
turns that list into it's arguments.

Alternativly (and this may not be useful) you can call a function with
a dictionary of arguments:

def bob(**kwargs):
    print kwargs

possible = {'a' : 10, 'b':5, 'c':-3}

>>> bob(**possible)
{'a': 10, 'c': -3, 'b': 5}


More information about the Python-list mailing list