Search code examples
pythonkeyword-argument

When using optional arguments when is it best to use **kwargs and best to use keywords?


If I had a function that had three or four optional keyword arguments is it best to use **kwargs or to specify them in the function definition?

I feel as def foo(required, option1=False, option2=False, option3=True) is much more clumsy looking than def foo(required, **kwargs).

However if I need to use these keywords as conditionals and they don't exist I will have KeyErrors being thrown and I feel like checking for the keys before each conditional is a bit messy.

def foo(required, **kwargs):
    print(required)
    if 'true' in kwargs and kwargs['true']:
        print(kwargs['true'])

foo('test', true='True')
foo('test2')

vs

def foo(required, true=None):
    print(required)
    if true:
        print(true)

foo('test', true='True')
foo('test2')

I am wondering what the most pythonic way is. I've got a function that I am working on that depending on the parameters passed will return different values so I am wondering the best way to handle it. It works now, but I wonder if there is a better and more pythonic way of handling it.


Solution

  • If the function is only using the parameters in its own operation, you should list them all explicitly. This will allow Python to detect if an invalid argument was provided in a call to your function.

    You use **kwargs when you need to accept dynamic parameters, often because you're passing them along to other functions and you want your function to accept any arguments that the other function needs, e.g. other_func(**kwargs)