call function with a dynamic list of arguments in python

Casper Deseyne picture Casper Deseyne · Aug 9, 2012 · Viewed 10.8k times · Source

I need to call a function that handles a list of arguments that can have default values:

example code:

web.input(name=None, age=None, desc=None, alert=None, country=None, lang=None)

How can I call web.input like this using a list or dictionary? I'm stuck at:

getattr(web, 'input').__call__()

Answer

Henry Gomersall picture Henry Gomersall · Aug 9, 2012
my_args = {'name': 'Jim', 'age': 30, 'country': 'France'}

getattr(web, 'input')(**my_args) # the __call__ is unnecessary

You don't need to use getattr either, you can of course just call the method directly (if you don't want to look up the attribute from a string):

web.input(**my_args)

You can do the same thing with lists:

my_args_list = ['Jim', 30, 'A cool person']
getattr(web, 'input')(*my_args_list)

is equivalent to

getattr(web, 'input')('Jim', 30, 'A cool person')