| An Introduction to Python by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 124 pages ISBN 0954161769 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
4.7.1 Default Argument Values
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
def ask_ok(prompt, retries=4, complaint='Yes or no!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
This function can be called either like this:
ask_ok('Do you really want to quit?') or like this:
ask_ok('Delete file?', 2).
This example also introduces the in keyword. This tests
whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
i = 5
def f(arg=i):
print arg
i = 6
f()
will print 5.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
This will print
[1]
[1, 2]
[1, 2, 3]
If you don't want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
| ISBN 0954161769 | An Introduction to Python | See the print edition |