简体   繁体   English

我可以将任意关键字参数传递给 function 吗?

[英]Can I pass arbitrary keyword argument into a function?

I am writing a generic function to plot univariate distributions:我正在编写一个通用的 function 到 plot 单变量分布:

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.而在matplotlib或任何绘图库中,里面有很多很多*args 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?我可以在哪里传递任何 arguments 而不是预定义的字典?

Arbitrary keyword arguments (conventionally known as kwargs) are an essential part of Python.任意关键字 arguments(通常称为 kwargs)是 Python 的重要组成部分。

Here's an example (note the syntax):这是一个示例(注意语法):

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

func(a=1, b=2)

Output: 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如您所见,实际传递的是对包含参数名称(键)及其关联值的字典的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以在 Python 包装函数中只传递关键字参数的关键字名称吗? - Can I pass just the keyword name of a keyword argument in a Python wrapper function? 打开字典以作为关键字参数传递时,如何将键映射到其他命名的关键字参数? - When unpacking a dictionary to pass as keyword arguments, how can I map a key to a differently named keyword argument? 如何编写python函数来接受*参数和关键字参数? - How can I write a python function to accept *arguments and a keyword argument? 如何将关键字传递给函数以使用默认参数 - how to pass a keyword to the function to use the default argument 将参数传递给类,该类成为函数的关键字 - Pass an argument to a class which becomes a keyword for a function 将相同的关键字参数传递给函数两次 - Pass same keyword argument to a function twice 我可以将异常作为参数传递给python中的函数吗? - Can I pass an exception as an argument to a function in python? 将关键字参数传递给关键字具有默认值的另一个函数 - Pass keyword argument to another function where the keyword has a default value 如何将关键字参数作为参数传递给函数? - How can I pass keyword arguments as parameters to a function? 如何在没有“lambda”关键字的情况下将方法作为函数参数传递? - How can I pass method as function parameter without 'lambda' keyword?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM