Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

6.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

    def ask_ok(prompt, retries=4, complaint='Yes or no!'):
        while 1:
            ok = raw_input(prompt)
            if ok in ('y', 'ye', 'yes'): return 1
            if ok in ('n', 'no', 'nop', 'nope'): return 0
            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).

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 or dictionary. 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

 
 
  Published under the terms of the Python License Design by Interspire