Chapter 7. Functions
Defining functions using the def statement is a cornerstone of all programs.
The goal of this chapter is to present some more advanced
and unusual function definition and usage patterns. Topics include
default arguments, functions that take any number of arguments,
keyword-only arguments, annotations, and closures. In addition, some
tricky control flow and data passing problems involving callback
functions are addressed.
7.1. Writing Functions That Accept Any Number of Arguments
Problem
You want to write a function that accepts any number of input arguments.
Solution
To write a function that accepts any number of positional arguments,
use a * argument. For example:
defavg(first,*rest):return(first+sum(rest))/(1+len(rest))# Sample useavg(1,2)# 1.5avg(1,2,3,4)# 2.5
In this example, rest is a tuple of all the extra positional arguments passed.
The code treats it as a sequence in performing subsequent calculations.
To accept any number of keyword arguments, use an argument that starts
with **. For example:
importhtmldefmake_element(name,value,**attrs):keyvals=['%s="%s"'%itemforiteminattrs.items()]attr_str=''.join(keyvals)element='<{name}{attrs}>{value}</{name}>'.format(name=name,attrs=attr_str,value=html.escape(value))returnelement# Example# Creates '<item size="large" quantity="6">Albatross</item>'make_element('item','Albatross',size='large',quantity=6)# Creates '<p><spam></p>'make_element('p','<spam>')
Here,