Can I pass arbitrary keyword argument into a function?

I am writing a generic function to plot univariate distributions:

univariate_subplot_params = {"nrows": 7, "ncols": 2, "figsize": (12, 24), "dpi": 80}
univariate_histplot_params = {"kde": True, "hue": config.target_col,
                              "legend": False, "palette": {1: config.colors[0], 0: config.colors[3]}}
univariate_fig_params = {"suptitle": "Coronary"}

def plot_univariate(df: pd.DataFrame, predictors: str, univariate_subplot_params: Dict[str, Any],
                    univariate_histplot_params: Dict[str, Any],
                    univariate_fig_params: Dict[str, Any]) -> None:
    """
    Take in continuous predictors and plot univariate distribution. 
    Note in this setting, we have kde=True.

    Args:
        df (pd.DataFrame): Dataframe.
        predictor (str): Predictor name.
    """

    fig, axs = plt.subplots(**univariate_subplot_params)

    for i, col in enumerate(predictors):
        sns.histplot(
            data=df,
            x=col,
            ax=axs[i % univariate_subplot_params["nrows"]][i // univariate_subplot_params["nrows"]],
            **univariate_histplot_params)
    plt.subplots_adjust(hspace=2)
    fig.suptitle(
        univariate_fig_params.get("suptitle", ""), y=1.01, fontsize="x-large"
    )
    fig.legend(df[config.target_col].unique())
    fig.tight_layout()
    plt.show()

And in matplotlib or any plotting libraries, there are many many *args inside. I would like to define the configuration for them so I can pass it in like the code above.

I am thinking if I can do the following:

def plot_univariate(df: pd.DataFrame, predictors: str, *args) -> None:
    """
    Take in continuous predictors and plot univariate distribution. 
    Note in this setting, we have kde=True.

    Args:
        df (pd.DataFrame): Dataframe.
        predictor (str): Predictor name.
    """

    fig, axs = plt.subplots(USE_ARGS)

    for i, col in enumerate(predictors):
        sns.histplot(
            data=df,
            x=col,
            USE_ARGS)
    plt.subplots_adjust(hspace=2)
    fig.suptitle(
        TITLE=USE_ARGS, y=1.01, fontsize="x-large"
    )
    fig.legend(df[config.target_col].unique())
    fig.tight_layout()
    plt.show()

Where I am able to pass in any arguments instead of pre-defined dictionaries?


Solution 1:

Arbitrary keyword arguments (conventionally known as kwargs) are an essential part of Python.

Here's an example (note the syntax):

def func(**kwargs):
    print(kwargs)

func(a=1, b=2)

Output:

{'a': 1, 'b': 2}

As you can see, what actually gets passed is a reference to a dictionary containing the argument names (keys) and their associated values