Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a dictionary as default arguments of a function

let’s say i have a function like this:

def foo (a = "a", b="b", c="c", **kwargs):
    #do some work

I want to pass a dict like this to the function as the only argument.

arg_dict = {
    "a": "some string"
    "c": "some other string"
}

which should change the values of the a and c arguments but b still remains the default value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

foo(**arg_dict)

**arg_dict is passed as the **kwargs and other arguments stay the default value.

>Solution :

You can unpack the arg_dict using ** operator.

>>> def foo (a = "a", b="b", c="c", **kwargs):
...     print(f"{a=}")
...     print(f"{b=}")
...     print(f"{c=}")
...     print(f"{kwargs=}")
... 
>>> arg_dict = {
...     "a": "some string",
...     "c": "some other string",
...     "addional_kwrag1": 1
... }
>>> 
>>> foo(**arg_dict)
a='some string'
b='b'
c='some other string'
kwargs={'addional_kwrag1': 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading