Online Book Reader

Home Category

Learning Python - Mark Lutz [463]

By Root 1418 0

starting with block

running test 1

reached

exited normally

starting with block

running test 2

raise an exception!

Traceback (most recent call last):

File "withas.py", line 20, in

raise TypeError

TypeError

Context managers are somewhat advanced devices for tool builders, so we’ll skip additional details here (see Python’s standard manuals for the full story—for example, there’s a new contextlib standard module that provides additional tools for coding context managers). For simpler purposes, the try/finally statement provides sufficient support for termination-time activities.

* * *

Note


In the upcoming Python 3.1 release, the with statement may also specify multiple (sometimes referred to as “nested”) context managers with new comma syntax. In the following, for example, both files’ exit actions are automatically run when the statement block exits, regardless of exception outcomes:

with open('data') as fin, open('res', 'w') as fout:

for line in fin:

if 'some key' in line:

fout.write(line)

Any number of context manager items may be listed, 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...

See Python 3.1 release notes for additional details.

* * *

Chapter Summary

In this chapter, we took a more detailed look at exception processing by exploring the statements related to exceptions in Python: try to catch them, raise to trigger them, assert to raise them conditionally, and with to wrap code blocks in context managers that specify entry and exit actions.

So far, exceptions probably seem like a fairly lightweight tool, and in fact, they are; the only substantially complex thing about them is how they are identified. The next chapter continues our exploration by describing how to implement exception objects of your own; as you’ll see, classes allow you to code new exceptions specific to your programs. Before we move ahead, though, let’s work though the following short quiz on the basics covered here.

Test Your Knowledge: Quiz

What is the try statement for?

What are the two common variations of the try statement?

What is the raise statement for?

What is the assert statement designed to do, and what other statement is it like?

What is the with/as statement designed to do, and what other statement is it like?

Test Your Knowledge: Answers

The try statement catches and recovers from exceptions—it specifies a block of code to run, and one or more handlers for exceptions that may be raised during the block’s execution.

The two common variations on the try statement are try/except/else (for catching exceptions) and try/finally (for specifying cleanup actions that must occur whether an exception is raised or not). In Python 2.4, these were separate statements that could be combined by syntactic nesting; in 2.5 and later, except and finally blocks may be mixed in the same statement, so the two statement forms are merged. In the merged form, the finally is still run on the way out of the try, regardless of what exceptions may have been raised or handled.

The raise statement raises (triggers) an exception. Python raises built-in exceptions on errors internally, but your scripts can trigger built-in or user-defined exceptions with raise, too.

The assert statement raises an AssertionError exception if a condition is false. It works like a conditional raise statement wrapped up in an if statement.

The with/as statement is designed to automate startup and termination activities that must occur around a block of code. It is roughly like a try/finally statement in that its exit actions run whether an exception occurred or not, but it allows a richer object-based protocol for specifying entry and exit actions.

Chapter 34. Exception Objects

So far, I’ve been deliberately vague about what an exception actually is. As suggested

Return Main Page Previous Page Next Page

®Online Book Reader