Chapter 3. Advanced Functions
In this chapter, we go beyond the basics of using functions. I’ll assume you can write functions with default argument values:
>>>
def
foo
(
a
,
b
,
x
=
3
,
y
=
2
):
...
return
(
a
+
b
)
/
(
x
+
y
)
...
>>>
foo
(
5
,
0
)
1.0
>>>
foo
(
10
,
2
,
y
=
3
)
2.0
>>>
foo
(
b
=
4
,
x
=
8
,
a
=
1
)
0.5
Notice the way foo()
is called the last time, with arguments out
of order, and everything specified by key-value pairs. Not everyone
knows that you can call most Python functions this way. So long as the
value of each argument is unambiguously specified, Python doesn’t care
how you call the function (and this case, we specify b
, x
, and a
out of order, letting y
be its default value). We will leverage this
flexibility later.
This chapter’s topics are useful and valuable on their own. And they are important building blocks for some extremely powerful patterns, which you will learn in later chapters. Let’s get started!
Accepting and Passing Variable Arguments
The foo()
function above can be called with two, three, or four arguments.
Sometimes you want to define a function that can take any number of
arguments—zero or more, in other words. In Python, it looks like
this:
# Note the asterisk. That's the magic part
def
takes_any_args
(
*
args
):
(
"Type of args: "
+
str
(
type
(
args
)))
(
"Value of args: "
+
str
(
args
))
Look carefully at the syntax here. takes_any_args()
is just like a
regular function, except you put an asterisk right before the argument
args
. Within the function, args
is a tuple:
>>> ...
Get Powerful Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.