Functions with named arguments
Previously, we used functions that have positional arguments. In a function like
def fun(foo, bar): print(2*foo+bar)
invoked by fun(2,3)
, the value of foo
becomes 2 and the
value of bar
becomes 3 because the first argument in the invocation
becomes the foo
and the second one becomes bar
. This
behavior becomes difficult if we have functions with many arguments, and believe me,
sometimes these are necessary. We can call the function the same way by explicitly
specifying which value is foo
and which value is bar
. We
do this by saying:
print(fun(bar=3, foo=2))
Now, we explicitly state which value goes into which variable, avoiding to have
to look up the function definition as might become necessary with positional arguments.
This is called
Functions with default arguments
You might have already used default arguments when you specified certain values in a Python-defined function. For example,print
has not only a variable
number of arguments, but it also has additional arguments that allow the programmer
to control the behavior of print. However, in the overwhelming majority of uses of
print, these arguments are always the same. Here is the synopsis of the print function
from the Python documentation:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
We have a variable called sep
that controls what is put between objects,
a variable called end
that controls what happens after the last object is
printed, the variable file
that allows us to control where we write, and
finally a variable flush
that controls when exactly we write to a file.
(Usually, writes to the file system are buffered, and by setting flush
to True
, you can try to induce the Operating System to overrule this
behavior. All of these arguments are usually not needed and therefore Python allows you
to just assume default behavior unless you set the values differently.
Defining our own default arguments is very simple. When we define the function
with def
, we put the arguments with default values last and put the default
values right after the argument name together with an equal sign. Here is an example:
def fun(a, b, c=1, d=False):
defines a function with two arguments called a and b, an additional argument c that
is 1 by default and a final argument d that defaults to False
.