7

I have a python function bar(a=None, b=None, c=None, d=None, e=None). I was wondering if it was possible to build the list of arguments I want to pass in, with a list or a string, or something.

I would have a list of attributes to look for and ideally I would simply loop over them and build the argument string.

For example, something like:

dict = {'a' : 5, 'c' : 3, 'd' :9} 
arg_string = ""
for k, v in dict.iteritems():
    arg_string += "{0}={1},".format(k, v)

bar(arg_string)

In this case I don't have any values to pass in for b and e, but the next time the program runs there may be.

Is this possible?

I know the string being built in the for loop will probably be invalid because of the comma at the end. But i didn't think it was necessary to write the handling for that

kumar5
  • 158
  • 1
  • 2
  • 8
  • The comma wouldn't be the problem, rather that you are calling `bar("a=5, c=3, d=9")` instead of `bar(a=5, c=3, d=9)`. – chepner Feb 22 '16 at 20:39
  • And, FWIW, trailing commas in python function calls are actually permissable (though ugly) -- `foo(a, b, c,)` is a syntactically valid function call. – mgilson Feb 22 '16 at 20:41

1 Answers1

26

The good news is that you don't even need a string. . .

mapping = {'a': 5, 'c': 3, 'd': 9} 
bar(**mapping)

should work. See the Unpacking Argument Lists (and surrounding material) in the official python tutorial.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Works like a charm with variable values as well, for instance I use it with mongoengine and I don't know the db value to update, so I handle it dynamically via `mapping = {dbEntry: value} myDBcollection.update(**mapping)` `dbEntry` can anything like `name`,`price`,`symbol`, etc – Michael Mar 16 '21 at 18:32