Ayoub ZAROU
Ayoub ZAROU

Reputation: 2417

Setting default parameters to a function from a dictionary

I'm trying to set parameters to a function from an arbitary dictionary. For example, if I have

d = {"a": 5, "b": 8}

I would want to define a function like this

def f(a = 5, b = 8) :
    print(a, b)

but whitout specifying the arguments , so, ultimately, I would want to do something like

def f(**d): 
    print(a,b)

but obviousely this wouldn't work, it just works when we call the function and not when it's defined, I would appreciate your help.

Upvotes: 1

Views: 195

Answers (3)

Ayoub ZAROU
Ayoub ZAROU

Reputation: 2417

In fact, I found a way to do what I first intended

d = {"a": 5, "b": 8}
def f(**kwargs) : 
   c = d.copy()
   c.update(kwargs)
   print(c["a"], c["b"])

This way I don't have to set the arguments one by one inside a function (I have a very large dictionary on the actual problem I'm trying to slove), and I don't have to set arguments to the function when defined

Upvotes: 0

Mark
Mark

Reputation: 92440

You can use both defaults and **kwargs in the function:

> def f(a=5, b=7, **kwargs):
>     print(a, b)

> f()
5, 7

> f(1, 2)
1, 2

> f(**{'a':20, 'b': 40})
20, 40

> f(**{'a':20})
20, 7

> f(a=300, **{'b':100})
300, 100

> # Okay
> f(3, **{'b':20})
3, 20

> # Not Okay
> f(3, **{'a':20})
TypeError: f() got multiple values for argument 'a'

Upvotes: 3

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

You can pass an arbitrary set of keyword arguments to a function by using the ** (dict unpacking) operator on a dict, and you can define a function to process a set of such keyword arguments by using the same operator. Once inside the function, the variable specified in the definition behaves like a dict. Example:

def f(**kwargs):
    print(kwargs["a"], kwargs["b"])

d = {"a": 5, "b": 8}
f(**d)
f(a=5, b=8)  # this behaves the same way

It's also generally safer to use the .get() function when dealing with a **kwargs dict, since that lets you set a default value in case the given key wasn't passed as a variable. For example:

def f(**kwargs):
    a = kwargs.get('a', 5)
    b = kwargs.get('b', 8)
    print(a, b)

f(a=9, b=13)  # prints 9 13
f()           # prints 5 8

Upvotes: 1

Related Questions