13

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__()
Casper Deseyne
  • 331
  • 1
  • 3
  • 11
  • possible duplicate of [Python: expand list to function arguments](http://stackoverflow.com/questions/7745952/python-expand-list-to-function-arguments) – lvc Aug 09 '12 at 10:54
  • 1
    Why `getattr(web, 'input').__call__()`? Just `web.input()` is fine. – Aesthete Aug 09 '12 at 10:58

3 Answers3

24
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')
Henry Gomersall
  • 8,434
  • 3
  • 31
  • 54
11

find here the relevant documentation

web.input(*list)
web.input(**kwargs)
tzelleke
  • 15,023
  • 5
  • 33
  • 49
  • 1
    @CasperDeseyne: If you got the answer you wanted it's accepted practice to mark it `accepted`. – jhoyla Aug 10 '12 at 08:34
6

You can use *args and **kwargs notation to pass tuples (positional) and dictionaries (named) arguments dynamically. The next code will act the same as your web.input(...).

keyword_args = {
   "name": None,
   "age": None,
   ...
}
web.input(**keyword_args)
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62