logo

... args kwargs.


Functions in python require arguments and you can be rather expressive with them. You can have functions that accept any number of arguments and there's many nice use-cases to be able to pass around keyword arguments. In this series of videos we'll explore how to use arguments (args) as well as keyword arguments (kwargs).


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 getting the newsletter.