Module (29%)
Section (20%)

Extended function argument syntax

When we talk about function arguments, we should recall the following facts:

  • some functions can be invoked without arguments;
  • functions may require a specific number of arguments with no exclusions; we have to pass a required number of arguments in an imposed order to follow function definition;
  • functions might have already defined default values for some parameters, so we do not have to pass all arguments as missing arguments, complete with defaults; parameters with default values are presented as keyword parameters;
  • we can pass arguments in any order if we are assigning keywords to all argument values, otherwise positional ones are the first ones on the arguments list.

Now let’s get familiar with the functions that can accept any arbitrary number of positional arguments and keyword arguments.

So far we've been using a few such functions, but we haven't focused much on that fact.

The most basic example is a print() function:

print() print(3) print(1, 20, 10) print('--', '++')

All presented invocations of the print() function end correctly, and the argument values are passed to the standard output.

Another interesting example can be presented with a list function:

a_list = list() b_list = list(10, 20, 43, 54, 23, 23, 34, 23, 2) print(a_list) print(b_list)

Similarly to the print() function, the list() function invocation accepts an arbitrary number of arguments. In fact, there are many, many other functions that accept arbitrary numbers of parameters, and you can spot them easily when reading third-party code.

How is it possible for Python functions to deal with a variable number of arguments? Can we prepare such functions ourselves?

The answer is yes, but it may look strange at first glance: *args and **kwargs. Don't worry, we'll tame them in a short moment.