Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
artfulrobot Avatar asked Mar 11 '15 12:03

artfulrobot


People also ask

How do you pass variable arguments in Python?

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.

How do you create a function argument in Python?

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.

How do you pass variable number of arguments to a function in Python?

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.


2 Answers

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)
like image 180
deceze Avatar answered Oct 29 '22 04:10

deceze


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
like image 23
thefourtheye Avatar answered Oct 29 '22 02:10

thefourtheye