Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function with a dynamic list of arguments in python

Tags:

python

web.py

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__()
like image 561
Casper Deseyne Avatar asked Aug 09 '12 10:08

Casper Deseyne


2 Answers

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')
like image 106
Henry Gomersall Avatar answered Oct 20 '22 00:10

Henry Gomersall


find here the relevant documentation

web.input(*list)
web.input(**kwargs)
like image 31
tzelleke Avatar answered Oct 19 '22 23:10

tzelleke