Call function with dynamic argument list in python

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

code example:

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 am stuck in:

 getattr(web, 'input').__call__() 
+6
source share
3 answers
 my_args = {'name': 'Jim', 'age': 30, 'country': 'France'} getattr(web, 'input')(**my_args) # the __call__ is unnecessary 

You also don't need to use getattr, you can just call the method directly (if you don't want to search for an attribute from a string):

 web.input(**my_args) 

You can do the same with lists:

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

equivalently

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

find relevant documentation here

 web.input(*list) web.input(**kwargs) 
+9
source

You can use * args and ** kwargs notation to dynamically pass tuples (positional) and dictionaries (named) arguments. The following code will act just like your web.input (...) .

 keyword_args = { "name": None, "age": None, ... } web.input(**keyword_args) 
+4
source

Source: https://habr.com/ru/post/922455/


All Articles