Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use varargs in designing a Python API?

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
like image 728
cdleary Avatar asked Jul 16 '09 10:07

cdleary


People also ask

Why do we use Varargs?

Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.

What is Varargs?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.

How do you use keyword arguments in Python?

Embrace keyword arguments in PythonConsider using the * operator to require those arguments be specified as keyword arguments. And remember that you can accept arbitrary keyword arguments to the functions you define and pass arbitrary keyword arguments to the functions you call by using the ** operator.

What is variable-length argument in Python?

Introduction to Variable-length Arguments in Python Variable-length arguments, abbreviated as varargs, are defined as arguments that can also accept an unlimited amount of data as input. The developer doesn't have to wrap the data in a list or any other sequence while using them.


1 Answers

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.

like image 54
Ants Aasma Avatar answered Sep 22 '22 02:09

Ants Aasma