简体   繁体   English

Function 参数最佳实践:dict vs kwargs

[英]Function parameter best practice: dict vs kwargs

I have a Python best practices question that I haven't been able to find a good answer to on the web (possibly due to deficient Googling skills).我有一个 Python 最佳实践问题,我无法在 web 上找到一个好的答案(可能是由于谷歌搜索技能不足)。 When defining a function that takes a variable number of key-value pairs, I could either define a parameter that takes a dict , like:在定义采用可变数量的键值对的 function 时,我可以定义一个采用dict的参数,例如:

def func(dict_param):
    for key, value in dict_param.items():
        # do stuff

or allow the function to take **kwargs :或允许 function 采取**kwargs

def func(**kwargs):
    for key, value in kwargs.items():
        # do stuff

My question is this: Are there any reasons to use a dict over **kwargs and vice versa?我的问题是:有什么理由在**kwargs上使用dict ,反之亦然? Does it depend?这取决于吗? What are the caveats of each?各有什么注意事项? What are best practices here?这里有哪些最佳实践?

Following the Zen of Python , which says:遵循Python 的禅宗,其中说:

Explicit is better than implicit.显式优于隐式。

either should not be used as a replacement for actually listing the function parameters in its signature.任何一个都不应用作在其签名中实际列出 function 参数的替代品。

Assuming that your use case is to pass around a large number of parameters, you would typically prefer the first form.假设您的用例是传递大量参数,您通常更喜欢第一种形式。 Instead, if are dealing with function for which you want to support a variable number of keyword arguments, you should use the second form.相反,如果要处理 function 并希望支持可变数量的关键字 arguments,则应使用第二种形式。

Note that, in general the two forms are not the same, in that the keys in the second form must be strings, ie:注意,一般两个forms是不一样的,第二种形式的key必须是字符串,即:

def func(dict_param):
    for key, value in dict_param.items():
        pass


def func2(**kwargs):
    for key, value in kwargs.items():
        pass


d = {1: 2, 3: 4}
func(d)
# Runs smoothly
func2(**d)
# TypeError: func2() keywords must be strings

When def func(dict_param) is used, this function will error if the parameter dict_param is not passed as an argument.当使用def func(dict_param)时,如果参数dict_param没有作为参数传递,这个 function 会出错。

However when def func(**kwargs) is used the dictionary paramter is optional and the function can run without being passed an argument (unless there are other arguments)但是,当使用def func(**kwargs)时,字典参数是可选的,并且 function 可以在不传递参数的情况下运行(除非有其他参数)

But as norok2 said,但正如 norok2 所说,

Explicit is better than implicit.显式优于隐式。

Therfore, you should always design your functions to try and avoid these ambigious parameters to avoid any potential type errors.因此,您应该始终设计您的函数来尽量避免这些模棱两可的参数,以避免任何潜在的类型错误。

Hope this helps:)希望这可以帮助:)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM