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

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

问题描述

有经验的时候,你应该preFER可变参数的函数签名您的API超过传递一个迭代,以功能有一个良好的规则? (可变参数是短期的可变参数或变数的论点,即 * ARGS

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

  os.path.join(first_component,其余*) -  GT;海峡

允许使用:

 分钟(迭代[,键= FUNC]) -  GT; VAL
分(A,B,C,... [,键= FUNC]) - GT; VAL

任何 / 所有只允许一个可迭代:

 的(迭代器) -  GT;布尔


解决方案

考虑一下,当你希望你的用户指定的参数为调用点code或具有单个值是常见的情况列表中使用可变参数。如果你希望你的用户能够从别的地方得到的参数,不要使用可变参数。有疑问时,宁可不使用可变参数的一面。

使用你的例子,为最常见的用例的 os.path.join 的是要有一个路径preFIX,并附加文件名/相对路径到它,所以调用通常看起来像 os.path.join(preFIX,SOME_FILE)的。在另一方面,的()的通常用于处理数据的列表,当你知道所有的元素,你不使用的的([​​A,B,C])的,您使用的 a或b或c

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)

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

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

Whereas min allows either:

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

Whereas any/all only permit an iterable:

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.

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天全站免登陆