5

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?

1

2 Answers 2

5
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ned Deily discusses a style that preserves the keyword=value style here in a similar topic.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.