Proper way to check if a specific parameter value was passed as kwargs

Viewed 64

Suppose I had a function that takes optional keyword arguments (**kwargs). I want to do three different things depending if (i) this argument was passed along with a specific value, (ii) it was passed without the specific value, (iii) it wasn't passed.

What I have so far. Example:

def myfunc(**kwargs):
    
  ... do stuff


myfunc(print_job=True)
# output: 
# Incoming print job. myfunc was called.

myfunc(print_job=False)
# output: 
# No incoming print jobs. myfunc was called.

myfunc()
# output: 
# myfunc was called.

What's the proper way to deal with kwargs in this case? Is it literally, checking for the specific value using two if-statements, like:

def myfunc(**kwargs):
    if 'print_job' in kwargs:
        if kwargs['print_job'] is True:
            #... do stuff
        else:
            # ... do stuff
    else:
        # ... do stuff

or is there other more Pythonic way?

2 Answers

I'd prefer to do this kind of things with 'get()'. It's way more simple instead of nested if else.

def myfunc(**kwargs):
        p = kwargs.get('printjob')

        if p is None:
                # printjob not passed
                print ('printjob not found')

        elif p is True:
                # printjob = True
                print ('yes')

        elif p is False:
                # printjob = False
                print ('no')
        else:
                # printjob is not boolean
                print ('unknown value')

Or you can write a helper function which will return you values of a certain arguments from kwargs. It will be very helpful if you have more arguments to query. then
def helper(key_list, kwargs):
        # do your stuff
        # or call other functions for execution
        # return something

def myfunc(**kwargs):
        helper(['printjob', 'arg2', 'arg3'], kwargs)

One way would be to use the KeyError in the logic.

def myfunc( **kwargs ): 
        try:     
            # if 'print_job' isn't a key in kwargs this throws an exception.
            if kwargs['print_job'] is True: 
                print( "'print_job' is True" ) 
            else: 
                print("'print_job' is not True but is:", kwargs['print_job']) 
        except KeyError:   # KeyError exception caught here
            print( "'print_job' not in kwargs.") # The no 'print_job' code

This is the 'Ask for forgiveness not for permission' principle. Catching the KeyError becomes part of the logic in the code.

Related