Search the Catalog
Python Pocket Reference, 2nd Edition

Python Pocket Reference, 2nd Edition

By Mark Lutz
2nd Edition November 2001
0-59600-001-8, Order Number: 0018
128 pages, $11.95

Sample Excerpt
Specific Statements

The following sections describe all Python statements. Each section lists the statement's syntax formats, followed by usage details. For compound statements, each appearance of a suite in a statement format stands for one or more other statements, possibly indented as a block under a header line. A suite must be indented under a header if it contains another compound statement (if, while, etc.); otherwise, it can appear on the same line as the statement header. The following are both valid constructs:

if x < 42:
    print x
    while x: x = x -1
 
if x < 42: print x

Assignment

target = expression
target1
= target2 = expression
target1
, target2 = expression1, expression2
target1
, target2,... = same-length-sequence
(target1, target2,...) = same-length-sequence
[target1, target2,...] = same-length-sequence

Stores references to objects in targets. Expressions yield objects. Targets may be simple names (X), qualified attributes (X.attr), or indexes and slices (X[i], X[i:j]).

The second format assigns expression object to each target. The third format pairs targets with expressions, left to right. The last three formats assign components of any sequence to corresponding targets, from left to right. The sequence on the right must be the same length, but can be any type.

Augmented assignment

As of Python 2.0, a set of additional assignment statement formats, listed in Table 13, are available. Known as "augmented assignment," these formats imply a binary expression plus an assignment. For instance, the following two formats are roughly equivalent:

X = X + Y
X += Y

but the reference to target X needs to be evaluated only once, and in-place operations may be applied for mutables as an optimization (e.g., list1 += list2 automatically calls list1.extend(list2), instead of the slower concatenation operation implied by +). Classes may overload in-place assignments with method names that begin with an "i" (e.g., __iadd__ for +=, __add__ for +). The format X //= Y (floor division) is new in 2.2.

Table 13: Augmented assignment statements (continued)

X += Y

X &= Y

X -= Y

X |= Y

X *= Y

X ^= Y

X /= Y

X »= Y

X %= Y

X «= Y

X **= Y

X //= Y

Expressions

expression
function([value, name=value, ...])
object.method([value, name=value, ...])

Any expression can appear as a statement (but statements cannot appear as expressions). Expressions are commonly used for running functions and for interactive-mode printing.

In function and method calls, actual arguments are separated by commas and are normally matched to arguments in function def headers by position. Calls may optionally list specific argument names in functions to receive passed values, by using the name=value keyword syntax.

apply( )-like call syntax

As of Python 2.0, special syntax can be used in function and method call argument lists to achieve the same effect as an apply( ) built-in function call. If args and kw are a tuple and a dictionary, respectively, the following are equivalent:

apply(f, args, kw)
f(*args, **kw)

Both formats call function f with positional arguments args and keyword arguments kw. The latter format is intended to be symmetric with function header arbitrary-argument syntax such as def f(*args, **kw):.

The print Statement

print [value [, value]* [,]]
print >> fileobj [, value [, value]* [,]]

Displays the printable representation of values on stdout stream (the current setting of sys.stdout). Adds spaces between values. Trailing comma suppresses linefeed normally added at end of list. Because print simply calls the write method of the object currently referenced by sys.stdout, the following is equivalent to print X:

import sys
sys.stdout.write(str(X) + '\n')

To redirect print text to files or class objects, reassign sys.stdout to any object with a write method:

sys.stdout = open('log', 'a')  # any object with a write(
)
print "Warning-bad spam!"  # goes to the object's write(
)

Extended print form

As of Python 2.0, the print statement may also name an open output file-like object to be the target of the printed text (instead of sys.stdout):

fileobj = open('log', 'a')
print >> fileobj, "Warning-bad spam!"

If the file object is None, sys.stdout is used. Because sys.stdout can be reassigned, the >> form is not strictly needed; however, it can often avoid both explicit write method calls and saving and restoring the original sys.stdout value around a redirected print.

The if Statement


if test: 
    suite
[elif test: 
    suite]*
[else: 
    suite]

Selects from among one or more actions (statement blocks). Runs suite associated with first if or elif test that is true, or else suite if all are false.

The while Statement


while test: 
    suite
[else: 
    suite]

General loops. Keeps running first suite while test at top is true. Runs else suite if loop exits without hitting a break statement.

The for Statement


for target in sequence: 
    suite
[else: 
    suite]

Sequence iteration. Assigns items in sequence to target and runs first suite for each. Runs else suite if loop exits without hitting a break statement. target may be anything that can appear on the left side of an "=" assignment statement (e.g., for (x, y) in tuplelist:).

In 2.2, works by first trying to obtain an iterator object with iter(sequence) and then calling that object's next( ) method repeatedly until StopIteration is raised (see "The yield Statement"). In earlier versions, or if no iterator object can be obtained (e.g., no __iter__ method is defined), works instead by repeatedly indexing sequence at successively higher offsets until an IndexError is raised.

The pass Statement

pass

Do-nothing placeholder statement, when syntactically necessary.

The break Statement

break 

Immediately exits closest enclosing while or for loop statement, skipping its associated else (if any).

The continue Statement

continue 

Immediately goes to the top of the closest enclosing while or for loop statement; resume in the loop header line.

The del Statement

del name
del name[i]
del name[i:j]
del name.attribute

Deletes names, items, slices, and attributes. Removes bindings.

The exec Statement

exec codestring [in globaldict [,
localdict]]

Compiles and runs code strings. codestring is any Python statement as a string; run in namespace containing the exec, or the global/local namespace dictionaries if specified (localdict defaults to globaldict). codestring can also be a compiled code object. Also see compile, eval, and execfile in the section "Built-in Functions."

The def Statement

def name([arg, arg=value,...
*arg, **arg]): 
    suite

Makes new functions. Creates a function object and assigns it to variable name. Each call to a function object generates a new, local scope, where assigned names are local to the function call by default (unless declared global). See also the section "Namespace and Scope Rules" later in the book. Arguments are passed by assignment; in a def header, they may be defined by any of the formats in Table 14.

Table 14: Argument definition formats

Argument format

Interpretation

arg

Simple name, matched by name or position

arg=value

Default value if arg not passed

*arg

Collects extra positional args

**arg

Collects extra keyword args passed by name

Mutable default argument values are evaluated once at def statement time, not on each call, so may retain state between calls (but classes are better state-retention tools):

>>> def grow(a, b=[]):
...     b.append(a)
...     print b
...
>>> grow(1); grow(2)
[1]
[1, 2]

lambda expressions

Functions may also be created with the lambda expression form: lambda arg, arg,...: expression. In lambda, arg is as in def, expression is the implied return value, and the generated function is simply returned as the lambda result to be called later, instead of being assigned to a variable. Because lambda is an expression, not a statement, it may be used in places that a def cannot be (e.g., within an argument list of a call).

The return Statement

return [expression]

Exits the enclosing function and returns expression value as the result of the call to the function. Hint: return a tuple for multiple-value function results.

The yield Statement

yield expression

Optional in 2.2; enable with from __future__ import generators. Suspend function state and return expression. On the next iteration, the function's prior state is restored, and control resumes immediately after the yield statement. Use a return statement with no value to end the iteration, or simply fall off the end of the function:

def generate_ints(N):
    for i in xrange(N):
        yield i

Generators and iterators

In 2.2, functions containing a yield statement are compiled as generators; when called, they return a generator object that supports the iterator interface (i.e., a next( ) method).

Iterators are objects returned by the iter(X) built-in function; they define a next( ) method, which returns the next item in the iteration or raises a StopIteration exception to end the iteration. Classes may provide an __iter__ method to overload the iter(X) built-in function call; if defined, the result is used to step through objects in for loops, rather than the traditional __getitem__ indexing overload scheme.

The global Statement

global name [, name]*

Namespace declaration: inside a class or function, treats appearances of name as references to a global (module-level) variable by that name--whether it is assigned or not. Because of Python scope rules, you need to declare only global names that are assigned within a def (global references are automatically found in the enclosing module).

The import Statement

import module [, module]*
import [package.]* module [, [package.]*
module]*
import module as name

Module access: imports a module as a whole. Modules contain names fetched by qualification (e.g., module.attribute). module names the target module--a Python file or compiled module located in a directory in sys.path (PYTHONPATH), without its filename suffix (e.g., omit the ".py"). Assignments at the top level of a Python file create module object attributes. The as clause assigns a variable name to the imported module object; useful to provide shorter synonyms for long module names.

Import operations compile a file's source to byte-code if needed (and save it in a .pyc file if possible), then execute the compiled code from top to bottom to generate module object attributes by assignment. Use the reload built-in function to force recompilation and execution of already-loaded modules; see also __import__ used by import, in the later section "Built-in Functions."

In the Jython implementation, imports may also name Java class libraries; Jython generates a Python module wrapper that interfaces with the Java library. In Standard (C) Python, imports may also load compiled C and C++ extensions.

Package imports

If used, package prefix names give enclosing directory names, and module dotted paths reflect directory hierarchies. An import of the form import dir1.dir2.mod loads the file at directory path dir1/dir2/mod.py, where dir1 must be contained by a directory listed on PYTHONPATH. Each directory through which an import descends must have a (possibly empty) __init__.py file that serves as the directory level's module namespace. All names assigned in __init__.py files become attributes of the directory's module object. Directory packages can resolve conflicts caused by the linear nature of PYTHONPATH.

The from Statement

from [package.]* module import name [,
name]*
from [package.]* module import *
from module import name as othername

Module names access: import (copy) variable names out of a module and use them later without enclosing module name qualification. The from mod import * format copies all names assigned at the top level of the module, except names with a single leading underscore or names not listed in the module's __all__ list-of-strings attribute (if defined).

If used, the as clause creates a name synonym. If used, package import paths work the same as in import statements (e.g., from dir1.dir2.mod import X), but the package path needs to be listed only in the from itself. Due to new scoping rules, the "*" format generates warnings in 2.2 if it appears nested in a function or class.

The from statement is also used to enable future (but still experimental) language additions, with from __future__ import featurename. This format must appear only at the top of a module file (preceded only by an optional doc string).

The class Statement

class name [( super [, super]* )]: 
    suite

Makes new class objects, which are factories for instance objects. Builds a new class object and assigns it to variable name. The class statement introduces a new local name scope, and all names assigned in the class statement generate class object attributes shared by all instances of the class. Important class features include the following (see also the later sections "Object-Oriented Programming" and "Operator Overloading Methods"):

The try Statement

try: 
    suite
[except [name [, data]]: 
    suite]*
[else:
    suite]

try: 
    suite
finally:
    suite

Catches exceptions. try statements may specify except clauses with suites that serve as handlers for exceptions raised during the try suite, else clauses that run if no exception occurs during the try suite, and finally clauses that run whether an exception happens or not.

Exceptions may be raised by Python, or explicitly (see also the raise statement). In except clauses, an extra variable name (data) can be used to intercept an extra data item raised with the exception name. Table 15 lists all the clauses that may appear in a try statement. finally cannot be mixed with except or else.

Table 15: try statement clause formats

Clause format

Interpretation

except:

Catch all (other) exceptions

except name:

Catch a specific exception only

except name, value:

Catch exception and extra data

except (name1, name2):

Catch any of the exceptions

else:

Run if no exceptions raised

finally:

Always run on the way out

Common variations include:

except classname, X:
Catch a class exception, and assign X to the raised instance.

except (name1, name2, name2), X:
Catch any of the exceptions, and assign X to the extra data.

The raise Statement

raise string
Matches except that names same string object.

raise string, data
Passes extra data object with exception (default is None); assigned to variable X in an except string, X: try statement clause.

raise instance
Same as raise instance.__class__, instance.

raise class, instance
Matches except that names this class, or any of its superclasses. Passes the class instance object as extra data with exception, to be assigned to X in an except class, X: try statement clause.

raise
Re-raises the current exception.

Triggers exceptions. Control jumps to the matching except clause of the most recently entered matching try statement, or to the top level of process (where it ends the program and prints a standard error message). May use to raise built-in or user-defined exceptions. Without arguments, re-raises the most recent exception. See also "Built-in Exceptions" for exceptions raised by Python.

Class exceptions

Exceptions may be string objects (first two formats) or class instances (second two formats). try statement except clauses that name string objects are matched by string identity (is), not by value (==). try statement except clauses that name classes catch an instance of that class, as well as any of its subclasses. All built-in exceptions are now class objects.

Class exceptions support exception categories, which may be easily extended. Because try statements catch all subclasses when they name a superclass, exception categories may be modified by altering the set of subclasses without breaking existing try statements. The raised instance object also provides storage for extra information about the exception:

class General:
    def __init__(self, x): 
        self.data = x
class Specific1(General): pass
class Specific2(General): pass
 
try:
    raise Specific1('spam')
except General, X:
    print X.data              # prints 'spam'

For backward compatibility with prior Python releases that only supported string exceptions, these raise formats are also allowed:

raise class [, arg]
raise class, (arg, arg,...)

These are the same as the instance format raise class([arg...]). The first format occurs when arg is not an instance of class. Python generates and raises an instance automatically, even if the raise lists only a class name (i.e., raise Class is the same as raise Class( )). It is suggested but not required that user-defined exceptions inherit from the built-in exception class Exception (see the section "Built-in Exceptions").

The assert Statement

assert expression [, message]

Debugging checks. If expression is false, raises AssertionError, passing message as an extra data item if specified. The -O command-line flag removes assertion logic.

Back to: Python Pocket Reference, 2nd Edition


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com