Section 11.1. What Are Functions?


11.1. What Are Functions?

Functions are the structured or procedural programming way of organizing the logic in your programs. Large blocks of code can be neatly segregated into manageable chunks, and space is saved by putting oft-repeated code in functions as opposed to multiple copies everywherethis also helps with consistency because changing the single copy means you do not have to hunt for and make changes to multiple copies of duplicated code. The basics of functions in Python are not much different from those of other languages with which you may be familiar. After a bit of review here in the early part of this chapter, we will focus on what else Python brings to the table.

Functions can appear in different ways ... here is a sampling profile of how you will see functions created, used, or otherwise referenced:

declaration/definition def foo(): print 'bar'

function object/reference foo

function call/invocation foo()

11.1.1. Functions versus Procedures

Functions are often compared to procedures. Both are entities that can be invoked, but the traditional function or "black box," perhaps taking some or no input parameters, performs some amount of processing, and concludes by sending back a return value to the caller. Some functions are Boolean in nature, returning a "yes" or "no" answer, or, more appropriately, a non-zero or zero value, respectively. Procedures are simply special cases, functions that do not return a value. As you will see below, Python procedures are implied functions because the interpreter implicitly returns a default value of None.

11.1.2. Return Values and Function Types

Functions may return a value back to their callers and those that are more procedural in nature do not explicitly return anything at all. Languages that treat procedures as functions usually have a special type or value name for functions that "return nothing." These functions default to a return type of "void" in C, meaning no value returned. In Python, the equivalent return object type is None.

The hello() function acts as a procedure in the code below, returning no value. If the return value is saved, you will see that its value is None:

>>> def hello(): ...     print 'hello world' >>> >>> res = hello() hello world >>> res >>> print res None >>> type(res) <type 'None'>


Also, like most other languages, you may return only one value/object from a function in Python. One difference is that in returning a container type, it will seem as if you can actually return more than a single object. In other words, you cannot leave the grocery store with multiple items, but you can throw them all in a single shopping bag, which you walk out of the store with, perfectly legal.

def foo():     return ['xyz', 1000000, -98.6] def bar():     return 'abc', [42, 'python'], "Guido"


The foo() function returns a list, and the bar() function returns a tuple. Because of the tuple's syntax of not requiring the enclosing parentheses, it creates the perfect illusion of returning multiple items. If we were to properly enclose the tuple items, the definition of bar() would look like this:

def bar():     return ('abc', [4-2j, 'python'], "Guido")


As far as return values are concerned, tuples can be saved in a number of ways. The following three ways of saving the return values are equivalent:

>>> aTuple = bar() >>> x, y, z = bar() >>> (a, b, c) = bar() >>> >>> aTuple ('abc', [(4-2j), 'python'], 'Guido') >>> x, y, z ('abc', [(4-2j), 'python'], 'Guido') >>> (a, b, c) ('abc', [(4-2j), 'python'], 'Guido')


In the assignments for x, y, z, and a, b, c, each variable will receive its corresponding return value in the order the values are returned. The aTuple assignment takes the entire implied tuple returned from the function. Recall that a tuple can be "unpacked" into individual variables or not at all and its reference assigned directly to a single variable. (Refer back to Section 6.18.3 for a review.)

In short, when no items are explicitly returned or if None is returned, then Python returns None. If the function returns exactly one object, then that is the object that Python returns and the type of that object stays the same. If the function returns multiple objects, Python gathers them all together and returns them in a tuple. Yes, we claim that Python is more flexible than languages like C where only one return value is allowed, but in all honesty, Python follows the same tradition. The programmer is just given the impression that he or she can return more than one object. Table 11.1 summarizes the number of items "returned" from a function, and the object that Python actually returns.

Table 11.1. Return Values and Types

Stated Number of Objects to Return

Type of Object That Python Returns

0

None

1

object

>1

tuple


Many languages that support functions maintain the notion that a function's type is the type of its return value. In Python, no direct type correlation can be made since Python is dynamically typed and functions can return values of different types. Because overloading is not a feature, the programmer can use the type() built-in function as a proxy for multiple declarations with different signatures (multiple prototypes of the same overloaded function that differ based on its arguments).



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net