artfulrobot
artfulrobot

Reputation: 21397

How to build arguments for a python function in a variable

I have a Python (3) function

def f(a, b, c=1, d=2):
    pass

I would like to build up a list of arguments in code. The actual use-case is to do this based on some command line argument parsing, but it's a general question (I'm fairly new to python) e.g.

myargs = {}
myargs['positionalParams'] = ['foo', 'bar']
myargs['c']=2
myargs['d']=3
f(myargs)

I know that I can do f(*somelist) to expand a list into separate args, but how to do that with a mix of positional and optional params? Or do I do it twice, once for positionals and once for a dict of others?

Upvotes: 5

Views: 5907

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

how to do that with a mix of positional and optional params?

You can pass values to positional arguments also with a dictionary by unpacking it like this

>>> def func(a, b, c=1, d=2):
...     print(a, b, c, d)
...     
... 
>>> myargs = {"a": 4, "b": 3, "c": 2, "d": 1}
>>> func(**myargs)
4 3 2 1

Or do I do it twice, once for positionals and once for a dict of others?

Yes. You can unpack the values for the positional arguments also, like this

>>> pos_args = 5, 6
>>> keyword_args = {"c": 7, "d": 8}
>>> func(*pos_args, **keyword_args)
5 6 7 8

Or you might choose to pass the values explicitly, like this

>>> func(9, 10, **keyword_args)
9 10 7 8

Upvotes: 2

deceze
deceze

Reputation: 522016

args = ['foo', 'bar']
kwargs = {'c': 2, 'd': 3}
f(*args, **kwargs)

Note that this will also do just fine:

kwargs = {'a': 'foo', 'b': 'bar', 'c': 2, 'd': 3}
f(**kwargs)

Upvotes: 5

Related Questions