Alireza Tabatabaeian
Alireza Tabatabaeian

Reputation: 15

is there a python trick to make kwargs.get a default method value if there is no key with that name exist?

for Example if I have a code like this

class myClass:
    def a(n=100):
        print(n)


def myFunc(**kwargs):
     myClass.a(n = kwargs.get('val', 20))

myFunc()

I want it to use default argument (n=100) when there is no 'val' in kwargs. is there a way to do this?

Upvotes: 0

Views: 83

Answers (1)

Barmar
Barmar

Reputation: 781300

Call myClass.a() with a kwargs dictionary. Then you can conditionally add the n element to that dictionary depending on whether your kwargs contains val.

def myFunc(**kwargs):
    args = {}
    if val in kwargs:
        args['n'] = kwargs['val']
    myClass.a(**args)

Upvotes: 3

Related Questions