什么时候应该在设计 Python API 时使用可变参数? [英] When should I use varargs in designing a Python API?

查看:28
本文介绍了什么时候应该在设计 Python API 时使用可变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于何时应该在 API 中使用可变参数函数签名而不是将可迭代对象传递给函数,是否有一个好的经验法则?(varargs"是variadic"或variable-number-of-arguments"的缩写;即*args)

Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. *args)

例如,os.path.join 有一个可变参数签名:

For example, os.path.join has a vararg signature:

os.path.join(first_component, *rest) -> str

min 允许:

min(iterable[, key=func]) -> val
min(a, b, c, ...[, key=func]) -> val

any/all 只允许迭代:

any(iterable) -> bool

推荐答案

当您希望用户将参数列表指定为调用站点的代码或具有单个值是常见情况时,请考虑使用可变参数.当您希望您的用户从其他地方获取参数时,请不要使用可变参数.如有疑问,最好不要使用可变参数.

Consider using varargs when you expect your users to specify the list of arguments as code at the callsite or having a single value is the common case. When you expect your users to get the arguments from somewhere else, don't use varargs. When in doubt, err on the side of not using varargs.

使用您的示例,os.path.join 最常见的用例是具有路径前缀并将文件名/相对路径附加到其上,因此调用通常看起来像 os.path.join(prefix, some_file).另一方面,any() 通常用于处理数据列表,当您知道所有不使用的元素时 any([a,b,c]),您使用 a 或 b 或 c.

Using your examples, the most common usecase for os.path.join is to have a path prefix and append a filename/relative path onto it, so the call usually looks like os.path.join(prefix, some_file). On the other hand, any() is usually used to process a list of data, when you know all the elements you don't use any([a,b,c]), you use a or b or c.

这篇关于什么时候应该在设计 Python API 时使用可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆