logo

... args kwargs: usecase



Notes

This is the function 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.

Feedback? See an issue? Something unclear? Feel free to mention it here.



If you want to be kept up to date, consider signing up for the newsletter.