The uses of ‘def function(*args)’ to accept an arbitrary number of positional arguments in Python

Pavol Kutaj
2 min readFeb 19, 2022

--

The aim of this page📝is to describe function definitions accepting an arbitrary number of positional arguments (not keyword here!)

1. *ARGS SYNTAX ENABLES THE ACCEPTANCE OF AN ARBITRARY NUMBER OF POSITIONAL ARGUMENTS

  • python function signatures can contain a special syntax called star args written as *args
  • i.e., the args argument is prefixed by a single asterisk
  • args is a widely accepted conventional name of the parameter, any other will work as well
  • since args is widely used for this case by convention, don't use it anywhere else
  • * is not used within the function body
  • args is called as a tuple you have to iterate over it
  • *args enters the function body as a tuple
  • i.e. you need to iterate over *args
  • *args must come after normal positional arguments
  • *args only collects positional positional arguments
  • another classroom example with iterator object

2. HOW TO DEAL WITH CALLS WITHOUT ARGUMENT?

  • if the above is called without an argument, the user will get a StopIteration exception such as
File "c:\multiplier.py", line 3, in multiplier
result = next(i)
StopIteration
  • this is confusing and it exposes an implementation detail about which clients of our function should be unaware

2.1. APPROACH 1: TRY/EXCEPT WITH EXCEPTION CHAINING

  • a typical exception class for an insufficient count of arguments is TypeError
  • use exception chaining to transform the exception type from StopIteration to TypeError
  • as a sidestep, in bash you have parameter expansion that allows you to return an argument count
  • it is part of the standard practice to have validation at the top of the function
if [[ ! $1 ]]; then
echo "Missing Argument"
exit 1
fi

2.2. APPROACH 2: ADD REGULAR POSITIONAL ARGUMENT FOR THE FIRST VALUE, *ARGS FOR ALL THE REST

  • another approach maybe adding a regular positional argument
  • the absence of an argument will produce an expected TypeError
  • another advantage is the simplicity, no need to use an iterator
  • RULE: based on the above advantages, do use regular positional arguments for the required parameters (even if there is >1) and *args to deal with any extra arguments

SOURCES

--

--

No responses yet