let’s say i have a function like this:
JavaScript
x
3
1
def foo (a = "a", b="b", c="c", **kwargs):
2
#do some work
3
I want to pass a dict
like this to the function as the only argument.
JavaScript
1
5
1
arg_dict = {
2
"a": "some string"
3
"c": "some other string"
4
}
5
which should change the values of the a
and c
arguments but b
still remains the default value.
since foo
is in an external library i don’t want to change the function itself.
is there any way to achieve this?
EDIT
to clarify foo
has both default arguments like a
and has keyword arguments
like **kwargs
when i do this:
JavaScript
1
2
1
foo(**arg_dict)
2
**arg_dict
is passed as the **kwargs
and other arguments stay the default value.
Advertisement
Answer
You can unpack the arg_dict
using **
operator.
JavaScript
1
18
18
1
>>> def foo (a = "a", b="b", c="c", **kwargs):
2
print(f"{a=}")
3
print(f"{b=}")
4
print(f"{c=}")
5
print(f"{kwargs=}")
6
7
>>> arg_dict = {
8
"a": "some string",
9
"c": "some other string",
10
"addional_kwrag1": 1
11
}
12
>>>
13
>>> foo(**arg_dict)
14
a='some string'
15
b='b'
16
c='some other string'
17
kwargs={'addional_kwrag1': 1}
18