[PYTHON] Variadic argument that accepts one or more arguments

The python variable length argument *, * variable length argument *, can omit the argument.

def func1(*items):
    return items

assert func1() == tuple()

If it is a problem if the argument is omitted, consider implementing such as sending `TypeError ()` when the argument is omitted.

def func2(*items):
    if len(items) > 0:
        return items
        raise TypeError("At least one argument required.")

-> TypeError

Sure, `` `func2``` is safe, but I don't know that the arguments were omitted until * Runtime error * was thrown. Therefore, you can enforce one or more arguments by implementing as follows. (* Syntax error *)

def func3(item, *items):
    return (item, ) + items

You can do it efficiently by using itertools.chain.

from itertools import chain

def func4(item, *items):
    return tuple(chain((item, ), items))

Both implementations have the same output if they take one or more arguments. If you don't allow omission of arguments, `func3``` and func4``` are easier than `func1```.

Recommended Posts

Variadic argument that accepts one or more arguments
Variadic argument
In Python, create a decorator that dynamically accepts arguments Create a decorator