fair-software badge build workflow pypi badge DOI

kwandl: Keyword arguments handled


Install kwandl using pip:

python3 -m pip install kwandl

To install the most recent development version directly from the GitHub repository run:

python3 -m pip install git+https://github.com/egpbos/kwandl.git


kwandl is essentially a box of magic tricks to make working with kwargs smoother.

Forward passing only relevant kwargs

Say you have a function top which takes **kwargs and passes them on to ding and boop:

def top(**kwargs):

Only problem is: ding and boop have different sets of keyword arguments:

def ding(dingo=1, dinga=2):

def boop(boopie=3, boonk=4):

This means top(dingo="blurg", boonk=None) will fail with a TypeError, because boonk will be passed to ding and dingo will be passed to boop, both of which are invalid.

kwandl solves this for you with one simple decorator:

def top(**kwargs):

This Just Works™.

It does so by modifying the abstract syntax tree (AST) of the function calls with kwargs as argument so that kwargs is effectively replaced by kwandl.get_kwargs_applicable_to_function(ding, kwargs) (or boop instead of ding depending on the calling function). An alternative way to use this kwandl functionality then is to use get_kwargs_applicable_to_function directly:

def top(**kwargs):
    ding(**kwandl.get_kwargs_applicable_to_function(ding, kwargs))
    boop(**kwandl.get_kwargs_applicable_to_function(boop, kwargs))

Note, however, that @kwandl.forward does a bit more: it also checks whether kwargs contains keyword arguments that are a match to neither ding nor boop and raises a TypeError if so. A complete alternative notation for @kwandl.forward would then be:

def top(**kwargs):
    ding_kwargs = kwandl.get_kwargs_applicable_to_function(ding, kwargs)
    boop_kwargs = kwandl.get_kwargs_applicable_to_function(boop, kwargs)

    unexpected_keywords = set(kwargs) - set(ding_kwargs) - set(boop_kwargs)

    if unexpected_keywords:
        raise TypeError(f"top() got an unexpected keyword argument '{unexpected_keywords.pop()}'")


The motivation behind this package should now become clearer: the amount of boilerplate necessary to solve what in my mind should not be such a huge problem is … well, huge.


Documentation Status

For more details, see the full documentation on Readthedocs.


If you want to contribute to the development of kwandl, have a look at the contribution guidelines.


This package was created with Cookiecutter and the NLeSC/python-template.

Indices and tables