args kwargs logo args kwargs: usecase

1 2 3 4 5 6 7
Notes

It's important to recognize when these keyword arguments can be so useful. Let's have a look at the function below that uses **kwargs.

import json
import pathlib

def dict_to_config(dictionary, file="config.json", verbose=False, **kwargs):
    json_txt = json.dumps(dictionary, **kwargs)
    if verbose:
        print(json_txt)
    pathlib.Path(file).write_text(json_txt)

Imagine that we did not have those, then we code might look like;

import json
import pathlib

def dict_to_config(dictionary, file="config.json", verbose=False, indent=None, sort_keys=False):
    json_txt = json.dumps(dictionary, indent=indent, sort_keys=sort_keys)
    if verbose:
        print(json_txt)
    pathlib.Path(file).write_text(json_txt)

And this is just for two parameters of json.dumps. Using **kwargs here will just make your code a whole lot simpler.