Linux/Unix > Python Essential Reference, Second Edition > 6. Functions and Functional Programming > Functions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104016132040103212187138

### Functions

Functions are defined with the `def` statement:

    def add(x,y):
        return x+y

Invoke the function by writing the function name followed by a tuple of function arguments, such as `a = add(3,4)`. The order and number of arguments must match those given in the function definition. If a mismatch exists, a `TypeError` exception is raised.

By assigning values, you can attach default arguments to function parameters:

    def foo(x,y,z = 42):

When a function defines a parameter with a default value, that parameter and all the parameters that follow are optional. If values are not assigned to all the optional parameters in the function definition, a `SyntaxError` exception is raised.

Default parameter values are always set to the objects that were supplied as values when the function was defined. For example:

    a = 10
    def foo(x = a):
        print x

    a = 5               # Reassign 'a'.
    foo()               # Prints '10' ((default value not changed)

However, the use of mutable objects as default values can lead to unintended behavior:

    a = [10]
    def foo(x = a):
        print x
    a.append(20)
    foo()              # Prints '[10, 20]'

A function can accept a variable number of parameters if an asterisk (`*`) is added to the last parameter name:

    def fprintf(file, fmt, *args):
        file.write(fmt % args)

    # Use fprintf. args gets (42, "hello world", 3.45)
    fprintf(out,"%d %s %f", 42, "hello world", 3.45)

In this case, all the remaining arguments are placed into the `args` variable as a tuple. To pass a tuple `args` to another function as if they were parameters, the `*args` syntax can be used as follows:

    def printf(fmt, *args):
            # Call another function and pass along args
            fprintf(sys.stdout, fmt, *args)

You can also pass function arguments by explicitly naming each parameter and specifying a value:

    def foo(w,x,y,z):
        print w,x,y,z

    # Keyword invocation
    foo(x=3, y=22, w='hello', z=[1,2])

With keyword arguments, the order of the parameters doesn’t matter. However, unless you’re using default values, you must explicitly name all the function parameters. If you omit any of the required parameters or if the name of a keyword doesn’t match any of the parameter names in the function definition, a `TypeError` exception is raised.

Positional arguments and keyword arguments can appear in the same function call, provided that all the positional arguments appear first. For example:

    foo('hello', 3, z=[1,2], y=22)

If the last argument of a function definition begins with `**`, all the additional keyword arguments (those that don’t match any of the parameter names) are placed in a dictionary and passed to the function. For example:

    def spam(**parms):
        print "You supplied the following args:"
        for k in parms.keys():
            print "%s = %s" % (k, parms[k])

    spam(x=3, a="hello", foobar=(2, 3))

You can combine extra keyword arguments with variable-length argument lists, as long as the `**` parameter appears last:

    # Accept variable number of positional or keyword arguments
    def spam(x, *args, **keywords):
        print x, args, keywords

Keyword arguments can also be passed to another function using the `**keywords` syntax:

    def callfunc(func, *args, **kwargs):
        print args
        print kwargs
        func(*args, **kwargs)

Finally, starting in Python 2.1, functions and methods can have arbitrary attributes attached to them. For example:

    def foo():
        print "Hello world"

    foo.secure = 1
    foo.private = 1

Function attributes are stored in a dictionary that’s available as the `_ _dict_ _` attribute of a function or method.

The primary use of function attributes is in specialized applications such as parser generators or network applications that would like to attach additional information to a function. Previously, the docstring was the only place to store such information.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.