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)

The Assignment Statement

target = expression
target1 = target2 = expression
target1, target2 = expression1, expression2
target1 += expression
target1, target2,  ...  = same-length-iterable
(target1, target2, ...) = same-length-iterable
[target1, target2, ...] = same-length-iterable
target1, *target2, ...  = matching–length-iterable

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

The second format assigns an expression object to each target. The third format pairs targets with expressions, left to right. The last three formats assign components of any sequence (or other iterable) to corresponding targets, from left to right. The sequence or iterable on the right must be the same length but can be any type, unless a single starred-name appears in the targets on the left to collect arbitrarily many items (Python 3.0 extended sequence assignment, discussed ahead):

target1, *target2, ... = iterable

Augmented assignment

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

X = X + Y
X += Y

However, the reference to target X in the second format needs to be evaluated only once, and in-place operations can 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 can 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 as of version 2.2.

Table 1-13. Augmented assignment statements

X += Y

X &= Y

X -= Y

X |= Y

X *= Y

X ^= Y

X /= Y

X >>= Y

X %= Y

X <<= Y

X **= Y

X //= Y

Normal and extended sequence assignment

In Python 2.X and 3.0, any sequence (or other iterable) of values may be assigned to any sequence of names, as long as the lengths are the same. This basic sequence assignment form works in most assignment contexts:

>>> a, b, c, d = [1, 2, 3, 4]
>>> a, d
(1, 4)

>>> for (a, b, c) in [[1, 2, 3], [4, 5, 6]]:
...     print(a, b, c)
...
1 2 3
4 5 6

In Python 3.0, sequence assignment is extended to allow collection of arbitrarily many items, by prefixing one variable in the assignment target with a star; when used, sequence lengths need not match:

>>> a, *b = [1, 2, 3, 4]
>>> a, b
(1, [2, 3, 4])

>>> a, *b, c = [1, 2, 3, 4]
>>> a, b, c
(1, [2, 3], 4)

>>> *a, b = [1, 2, 3, 4]
>>> a, b
([1, 2, 3], 4)

>>> for (a, *b) in [[1, 2, 3], [4, 5, 6]]: print(a, b)
...
1 [2, 3]
4 [5, 6]

The Expression Statement

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

Any expression can appear on a line by itself as a statement (but statements cannot appear as expressions). Expressions are commonly used for calling functions and methods, and for interactive-mode printing. Expression statements are also the most common coding for yield expressions and Python 3.0 print() built-in function calls (though they are documented as specific statements in this book).

Call syntax

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

Arbitrary arguments call syntax

Special syntax can be used in function and method call argument lists to unpack arbitrarily many arguments. If pargs and kargs are a sequence (or other iterable) and a dictionary, respectively:

f(*pargs, **kargs)

This format calls function f with positional arguments from iterable pargs, and keyword arguments from dictionary kargs. For instance:

>>> def f(a, b, c, d): print(a, b, c, d)
...
>>> f(*[1, 2], **dict(c=3, d=4))
1 2 3 4

This syntax is intended to be symmetric with function header arbitrary-argument syntax such as def f(*pargs, **kargs). It is also flexible, since it can be easily combined with other positional and keyword arguments (e.g., g(1, 2, foo=3, bar=4, *args, **kw)).

In Python 2.X, the apply() built-in function achieves a similar effect but is removed as of Python 3.0:

apply(f, pargs, kargs)

See also The def Statement for more call syntax details.

The print Statement

Printing takes the form of a built-in function call in Python 3.0, which is commonly coded as an expression statement (on a line by itself). Its call signature is as follows:

print([value [, value]*] 
   [, sep=string] [, end=string] [, file=file])

Each value denotes an object to be printed. This call is configured by its three keyword-only arguments:

  • sep is a string to place between values (defaults to a space: ' ').

  • end is a string to place at the end of the text printed (defaults to a newline: ' ').

  • file is the file-like object to which text is written (defaults to standard output: sys.stdout).

Pass empty or custom strings to suppress space separators and line feeds, and pass a file or file-like object to redirect output in your script:

>>> print(2 ** 32, 'spam')
4294967296 spam

>>> print(2 ** 32, 'spam', sep='')
4294967296spam

>>> print(2 ** 32, 'spam', end=' '), print(1, 2, 3)
4294967296 spam 1 2 3

>>> print(2 ** 32, 'spam', sep='', file=open('out', 'w'))
>>> open('out').read()
'4294967296spam
'

Because by default 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) + '
')

To redirect print text to files or class objects, either pass any object with a write method to the file keyword argument as shown earlier, or reassign sys.stdout to any such object:

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

Because sys.stdout can be reassigned, the file keyword argument 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 when the original stream is still required. See also Built-in Functions.

Python 2.X print statements

In Python 2.X, printing is a specific statement instead of a built-in function, of the following form:

print [value [, value]* [,]]
print >> file [, value [, value]* [,]]

The Python 2.X print statement displays the printable representation of values on the stdout stream (the current setting of sys.stdout) and adds spaces between values. The trailing comma suppresses the linefeed that is normally added at the end of a list, and is equivalent to using end=' ' in Python 3.0:

>>> print 2 ** 32, 'spam'
4294967296 spam

>>> print 2 ** 32, 'spam',; print 1, 2, 3
4294967296 spam 1 2 3

The Python 2.X print statement can 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. This Python 2.X >> syntax is equivalent to the file=F keyword argument in Python 3.0. There is no equivalent to sep=S in Python 2’s statement.

To use the Python 3.0 printing function in Python 2.X, run the following:

from __future__ import print_function

The if Statement

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

The if statement selects from among one or more actions (statement blocks), and it runs the suite associated with the first if or elif test that is true, or the else suite if all are false.

The while Statement

while test:
    suite
[else:
    suite]

The while loop is a general loop that keeps running the first suite while the test at the top is true. It runs the else suite if the loop exits without hitting a break statement.

The for Statement

for target in iterable:
    suite
[else:
    suite]

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

Since Python 2.2, this works by first trying to obtain an iterator object I with iter(iterable) and then calling that object’s I.__next__() method repeatedly until StopIteration is raised (I.__next__() is named I.next() in Python 2); see The yield Statement for more on iteration. In earlier versions, or if no iterator object can be obtained (e.g., no __iter__ method is defined), this works instead by repeatedly indexing iterable at successively higher offsets until an IndexError is raised.

The pass Statement

pass

This is a do-nothing placeholder statement, and is used when syntactically necessary. In Python 3.X only, ellipses (...) can achieve similar effects.

The break Statement

break

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

The continue Statement

continue

This immediately goes to the top of the closest enclosing while or for loop statement; it resumes in the loop header line.

The del Statement

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

The del statement deletes names, items, slices, and attributes, as well as removes bindings. In the last three forms, name can actually be any expression (with parentheses if required for priority). For instance: del a.b()[1].c.d.

The def Statement

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

The def statement makes new functions. It 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. Arguments are passed by assignment; in a def header, they can be defined by any of the four formats in Table 1-14.

The argument forms in Table 1-14 can also be used in a function call, where they are interpreted as shown in Table 1-15 (see The Expression Statement for more on function call syntax).

Table 1-14. Argument formats in definitions

Argument format

Interpretation

arg

Matched by name or position

arg=value

Default value if arg is not passed

*arg

Collects extra positional args as a new tuple

**arg

Collects extra keyword args passed as a new dictionary

*name, arg[=value]

Python 3.0 keyword-only arguments after *

*, arg[=value]Same as prior line

Table 1-15. Argument formats in calls

Argument format

Interpretation

arg

Positional argument

arg=value

Keyword (match by name) argument

*arg

Sequence (or other iterable) of positional arguments

**arg

Dictionary of keyword arguments

Python 3.0 keyword-only arguments

Python 3.0 generalizes function definition to allow keyword-only arguments, which must be passed by keyword, and are required if not coded with defaults. Keyword-only arguments are coded after the *, which may appear without a name if there are keyword-only arguments but not arbitrary positionals:

>>> def f(a, *b, c): print(a, b, c)  # c required keyword
...
>>> f(1, 2, c=3)
1 (2,) 3

>>> def f(a, *, c=None): print(a, c) # c optional keyword
...
>>> f(1)
1 None
>>> f(1, c='spam')
1 spam

Python 3.0 function annotations

Python 3.0 also generalizes function definition to allow arguments and return values to be annotated with object values for use in extensions. Annotations are coded as :value after the argument name and before a default, and ->value after the argument list. They are collected into an __annotations__ attribute, but are not otherwise treated as special by Python itself:

>>> def f(a:99, b:'spam'=None) -> float:
...     print(a, b)
...
>>> f(88)
88 None
>>> f.__annotations__
{'a': 99, 'b': 'spam', 'return': <class 'float'>}

lambda expressions

Functions can also be created with the lambda expression form which creates a new function object and returns it to be called later, instead of assigning it to a name:

lambda arg, arg,...: expression

In lambda, arg is as in def, expression is the implied return value of later calls. Because lambda is an expression, not a statement, it can be used in places that a def cannot (e.g., within a dictionary literal expression, or an argument list of a function call). Because lambda computes a single expression instead of running statements, it is not intended for complex functions.

Defaults and attributes

Mutable default argument values are evaluated once at def statement time, not on each call, and so can retain state between calls. However, some consider this behavior to be a caveat, and classes and enclosing scope references are often better state-retention tools; use None defaults for mutable and explicit tests to avoid changes as shown in the following’s comments:

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

Both Python 2.X and 3.0 also support attachment of arbitrary attributes to functions, as another form of state retention (though attributes support only per-function-object state, which is only per-call if each call generates a new function):

>>> grow.food = 'spam'
>>> grow.food
'spam'

Function and method decorators

As of Python 2.4, function definitions can be preceded by a declaration syntax that describes the function that follows. Known as decorators and coded with an @ character, these declarations provide explicit syntax for functional techniques. The function decorator syntax:

@decorator
def F():
    ...

is equivalent to this manual name rebinding:

def F():
    ...
F = decorator(F)

The effect is to rebind the function name to the result of passing the function through the decorator callable. Function decorators may be used to manage functions, or later calls made to them (by using proxy objects). Decorators may be applied to any function definition, including methods inside a class:

class C:
    @decorator
    def M():            # same as M = decorator(M)
        ...

More generally, the following nested decoration:

@A
@B
@C
def f(): ...

is equivalent to the following nondecorator code:

def f(): ...
f = A(B(C(f)))

Decorators may also take argument lists:

@spam(1,2,3)
def f(): ...

In this case spam must be a function returning a function (known as a factory function); its result is used as the actual decorator. Decorators must appear on the line before a function definition, and cannot be on the same line (e.g., @A def f(): ... is illegal).

Because they accept and return callables, some built-in functions, including property(), staticmethod(), and classmethod(), may be used as function decorators (see Built-in Functions). Decorator syntax is also supported for classes in Python 2.6 and 3.0 and later; see The class Statement.

The return Statement

return [expression]

The return statement exits the enclosing function and returns an expression value as the result of the call to the function. The expression defaults to None if it’s omitted. Hint: return a tuple for multiple-value function results.

The yield Statement

yield expression

The yield expression, commonly coded as an expression statement (on a line by itself), suspends function state and returns an 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 generateSquares(N):
    for i in range(N):
        yield i ** 2

>>> G =  generateSquares(5)
>>> list(G)                     # force results generation
[0, 1, 4, 9, 16]

When used as an expression, yield returns the object passed to the generator’s send() method at the caller (e.g., A = yield X), and must be enclosed in parenthesis unless it is the only item on the right of = (e.g., A = (yield X) + 42). In this mode, values are sent to a generator by calling send(value); the generator is resumed, and the yield expression returns value. If the regular __next__() method or next() built-in function is called to advance, yield returns None.

Generators also have a throw(type) method to raise an exception inside the generator at the latest yield, and a close() method that raises a new GeneratorExit exception inside the generator to terminate the iteration. yield is standard as of version 2.3 and later; generator send(), throw(), and close() methods are available as of Python 2.5.

Generators and iterators

Functions containing a yield statement are compiled as generators; when called, they return a generator object that supports the iterator protocol to produce results on demand. 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.

All iteration contexts including for loops and comprehensions automatically use the iteration protocol to step through collections. In addition, the next(I) built-in function automatically calls I.__next__() to simplify manual iteration loops.

Classes can provide an __iter__() method to intercept the iter(X) built-in function call; if defined, its result has a __next__() method used to step through results in iteration contexts. If no __iter__() is defined, the __getitem__() indexing method is used as a fallback to iterate until IndexError.

In Python 2.X, the I.__next__() method is named I.next(), but iteration works the same otherwise. The next() function calls the I.next() method in 2.6. See also Generator expressions for related tools.

The global Statement

global name [, name]*

The global statement is a namespace declaration: when used inside a class or function definition statement, it causes all appearances of name in that context to be treated as references to a global (module-level) variable of that name—whether name is assigned or not, and whether name already exists or not.

This statement allows globals to be created or changed within a function or class. Because of Python’s scope rules, you need to declare only global names that are assigned; undeclared names are made local if assigned, but global references are automatically located in the enclosing module. See also Namespace and Scope Rules.

The nonlocal Statement

nonlocal name [, name]*

Available in Python 3.0 only.

The nonlocal statement is a namespace declaration: when used inside a nested function, it causes all appearances of name in that context to be treated as references to a local variable of that name in an enclosing function’s scope—whether name is assigned or not.

name must exist in an enclosing function; this statement allows it to be changed by a nested function. Because of Python’s scope rules, you need to declare only nonlocal names that are assigned; undeclared names are made local if assigned, but nonlocal references are automatically located in enclosing functions. See also Namespace and Scope Rules.

The import Statement

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

The import statement provides module access: it imports a module as a whole. Modules in turn contain names fetched by qualification (e.g., module.attribute). 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; it is useful to provide shorter synonyms for long module names.

module names the target module—usually a Python source file or compiled module—which must be located in a directory in sys.path. The module is given without its filename suffix (.py and other extensions are omitted). The sys.path module import search path is a directory list initialized from the program’s top-level directory, PYTHONPATH settings, .pth path file contents, and Python defaults.

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 imp.reload() built-in function to force recompilation and execution of already-loaded modules; see also __import__ used by import in the section Built-in Functions.

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

Package imports

If used, the package prefix names give enclosing directory names, and module dotted paths reflect directory hierarchies. An import of the form import dir1.dir2.mod generally loads the module file at directory path dir1/dir2/mod.py, where dir1 must be contained by a directory listed on the module search path sys.path.

Each directory listed in an import statement must have a (possibly empty) __init__.py file that serves as the directory level’s module namespace. This file is run on the first import through the directory, and 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.

See also Package relative import syntax.

The from Statement

from [package.]* module import name [, name]*
from [package.]* module import *
from [package.]* module import name as othername
from [package.]* module import (name1, name2, ...)

The from statement imports variable names from a module so that you can use those names later without the need to qualify them with their module name. 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 version 2.2 if it appears nested in a function or class (this generates errors in Python 3.0).

As of Python 2.4, the names being imported from a module can be enclosed in parentheses to span multiple lines without backslashes. As of Python 3.0, from module import * form is invalid within a function, because it makes it impossible to classify name scopes at definition time.

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

Package relative import syntax

In Python 3.0, the from statement (but not import) may use leading dots in module names to specify that imports be relative to the package directory in which the importing module resides:

from module import name [, name]*    # sys.path: abs
from . import module [, module]*     # pkg dir only: rel
from .module import name [, name]*   # pkg dir only: rel
from .. import module [, module]*    # parent dir in pkg
from ..module import name [, name]*  # parent dir in pkg

The leading-dots syntax works to make imports explicitly package-relative in both Python 3.0 and 2.6. For imports without the dots syntax, the package’s own directory is searched first in Python 2.6, but not in Python 3.0. To enable Python 3.0 package import semantics in Python 2.6, use:

from __future__ import  absolute_import

Absolute package imports, relative to a directory on sys.path, are generally preferred over both implicit package-relative imports in Python 2.X, and explicit package-relative import syntax in both Python 2.X and 3.0.

The class Statement

[decoration]
class name [ ( super [, super]* [, metaclass=M] ) ]:
    suite

The class statement makes new class objects, which are factories for instance objects. The new class object inherits from each listed super class in the order given, and is assigned 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 sections Object-Oriented Programming and Operator Overloading Methods):

  • Superclasses (also known as base classes) from which a new class inherits attributes are listed in parentheses in the header (e.g., class Sub(Super1, Super2):).

  • Assignments in the suite generate class attributes inherited by instances: nested def statements make methods, while assignment statements make simple class members.

  • Calling the class generates instance objects. Each instance object may have its own attributes, and inherits the attributes of the class and all of its superclasses.

  • Method functions receive a special first argument, usually called self, which is the instance object that is the implied subject of the method call, and gives access to instance state information attributes. The staticmethod() and classmethod() built-ins support additional kinds of methods, and Python 3.X methods may be treated as simple functions when called through a class.

  • Specially named __X__ method definitions intercept built-in operations.

Class decorators in Python 2.6 and 3.0

In Python 2.6, 3.0, and later, decorator syntax can be applied to class statements, in addition to function definitions. The class decorator syntax:

@decorator
class C:
   def meth():
       ...

is equivalent to this manual name rebinding:

class C:
     def meth():
       ...
C = decorator(C)

The effect is to rebind the class name to the result of passing the class through the decorator callable. Like function decorators, class decorators may be nested and support decorator arguments. Class decorators may be used to manage classes, or later instance-creation calls made to them (by using proxy objects).

Metaclasses

Metaclasses are classes that generally subclass from the type class, in order to customize creation of class objects themselves:

class Meta(type):
    def __new__(meta, cname, supers, cdict):
        # run by inherited type.__call__
        return type.__new__(meta, cname, supers, cdict)

In Python 3.0, classes define their metaclasses using keyword arguments in class headers:

class C(metaclass=Meta): ...

In Python 2.X, use class attributes instead:

class C:
    __metaclass__ = Meta
    ...

See also type() in Built-in Functions for the mapping from class statements.

The try Statement

try:
    suite
except [type [as value]]:       # [, value] in Python 2
    suite
[except [type [as value]]:
    suite]*
[else:
    suite]
[finally:
    suite]

try:
    suite
finally:
    suite

The try statement catches exceptions. try statements can 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. except clauses catch and recover from exceptions, and finally clauses define termination actions.

Exceptions can be raised by Python, or explicitly (see also the raise statement discussed in the next section, The raise Statement). In except clauses, type is an expression giving the exception class to be caught, and an extra variable name value can be used to intercept the instance of the exception class that was raised. Table 1-16 lists all the clauses that can appear in a try statement.

The try must have either an except or a finally, or both. The order of its parts must be: tryexceptelsefinally, where the else and finally are optional, and there may be zero or more except, but there must be at least one except if an else appears. finally interacts correctly with return, break, and continue (if any of these pass control out of the try block, the finally clause is executed on the way out).

Table 1-16. try statement clause formats

Clause format

Interpretation

except:

Catch all (or all other) exceptions

except type:

Catch a specific exception only

except type as value:

Catch exception and its instance

except (type1, type2):

Catch any of the exceptions

except (type1, type2) as value:

Catch any of the exceptions and its instance

else:

Run if no exceptions are raised

finally:

Always run this block on the way out

Common variations include the following:

except classname as X:

Catch a class exception, and assign X to the raised instance. X gives access to any attached state information attributes, print strings, or callable methods on the instance raised. For older string exceptions, X is assigned to the extra data passed along with the string (string exceptions are removed in Python 3.0 and 2.6).

except (type1, type2, type3) as X:

Catch any of the exceptions named in a tuple, and assign X to the extra data.

See also the sys.exc_info() call in The sys Module for generic access to the exception class and instance (a.k.a., type and value) after an exception is raised.

Python 2.X try statement forms

In Python 2.X, try statements work as described, but the as clause used in except handlers to access the raised instance is coded with a comma instead:

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

In Python 3.0, the raise statement takes the following forms:

raise instance [from otherexc]

Raise a manually created instance of a class (e.g., raise Error(args)).

raise class [from otherexc]

Make and raise a new instance of class (equivalent to raise class()).

raise

Re-raise the most recent exception.

The raise statement triggers exceptions. You can use it to explicitly raise either built-in exceptions, or user-defined exceptions. Without arguments, raise re-raises the most recent exception. See also Built-in Exceptions for exceptions raised by Python.

On a raise, control jumps to the matching except clause of the most recently entered matching try statement, or to the top level of the process (where it ends the program and prints a standard error message). The instance object raised is assigned to the as variable in the matching except clause (if given).

The optional from clause allows exception chaining in Python 3.0 (only): otherexc is another exception class or instance, and is attached to the raised exception’s __cause__ attribute. If the raised exception is not caught, Python prints both exceptions as part of the standard error message.

Class exceptions

In Python 3.0 and 2.6 all exceptions are identified by classes, which must be derived from the built-in Exception class (in 2.6 this derivation is required of new-style classes only). The Exception superclass provides default display strings and constructor argument retention in tuple attribute args.

Class exceptions support exception categories, which can be easily extended. Because try statements catch all subclasses when they name a superclass, exception categories can 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(Exception):
    def __init__(self, x):
        self.data = x

class Specific1(General): pass
class Specific2(General): pass

try:
    raise Specific1('spam')
except General as X:
    print(X.data)             # prints 'spam'

Python 2.X raise statement forms

Prior to Python 2.6, Python 2.X allows exceptions to be identified with both strings and classes. Because of this, its raise statements may take the following forms, many of which exist for backward compatibility:

raise string

Matches an except handler clause that names the raised string object.

raise string, data

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

raise instance

This is the same as raise instance.__class__, instance.

raise class, instance

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

raise class

Same as raise class() (makes an instance of class).

raise class, arg

Same as raise class(arg) (makes an instance of class from non-instance arg).

raise class, (arg [, arg]*)

Same as raise class(arg, arg, ...) (makes an instance of class).

raise

Re-raises the current exception.

String exceptions were deprecated as of (and issues warnings in) Python 2.5. Python 2.X also allows a third item in raise statements, which must be a traceback object used instead of the current location as the place where the exception occurred.

The assert Statement

assert expression [, message]

The assert statement performs debugging checks. If expression is false, it raises AssertionError, passing message as an extra data item if specified. The -O command-line flag removes assertions (their tests are not run).

The with Statement

with expression [as variable]:      # Python 2.6 and 3.0
    suite

with expression [as variable]
        [, expression [as variable]]*:  # 3.1
    suite

The with statement wraps a nested block of code in a context manager, which ensures that block entry and/or exit actions are run. This is an alternative to try/finally for objects having context managers that perform termination actions whether exceptions are raised or not.

expression is assumed to return an object that supports the context management protocol. This object may also return a value that will be assigned to the name variable if the optional as clause is present. Classes may define custom context managers, and some built-in types such as files and threads provide context managers with exit actions that close files, release thread locks, etc.:

with open(r'C:miscscript', 'w') as myfile:
    ...process myfile, auto-closed on statement exit...

See Files for more details on file context manager usage, and Python manuals for other built-in types that support this protocol and statement, as well as details on the protocol itself.

This statement is supported as of Python 2.6 and 3.0, and may be enabled in 2.5 with the following:

from __future__ import with_statement

Multiple context managers in Python 3.1

In Python 3.1, this statement may also specify multiple (a.k.a. nested) context managers. Any number of context manager items may be separated by commas, and multiple items work the same as nested with statements. In general, the 3.1 and later code:

with A() as a, B() as b:
    ...statements...

is equivalent to the following, which works in 3.1, 3.0, and 2.6:

with A() as a:
    with B() as b:
        ...statements...

For example, in the following code both files’ exit actions are automatically run when the statement block exits, regardless of exception outcomes:

with open('data') as fin, open('results', 'w') as fout:
    for line in fin:
        fout.write(transform(line))

Python 2.X Statements

Python 2.X supports the print statement described above, does not support nonlocal, and does not support with until 2.6. In addition, raise, try, and def have the slightly different syntaxes in Python 2.X as noted above.

The following additional statement is available in Python 2.X only:

exec codestring [in globaldict [, localdict]]

The exec statement compiles and runs code strings. codestring is any Python statement (or multiple statements separated by newlines) as a string; it is run in a 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 the Python 2.X execfile() in Built-in Functions.

In Python 3.0, this statement becomes the exec() function (see Built-in Functions). The backward- and forward-compatible syntax exec(a, b, c) is also accepted in Python 2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset