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?
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
To pass a variable number of arguments to a function in Python, use the special syntax *args in the function specification. It is used to pass a variable-length, keyword-free argument list.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With