12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

traps programming errors itself, there is usually no need to code asserts to catchthings like out-of-bounds indexes, type mismatches, and zero divides:def reciprocal(x):assert x != 0return 1 / x# A useless assert!# <strong>Python</strong> checks for zero automaticallySuch asserts are generally superfluous—because <strong>Python</strong> raises exceptions on errorsautomatically, you might as well let it do the job for you. * For another example ofcommon assert usage, see the abstract superclass example in Chapter 24; there, weused assert to make calls to undefined methods fail with a message.with/as Context Managers<strong>Python</strong> 2.6 (still in the future as this edition is being written) will introduce a newexception-related statement—the with, and its optional as clause. This statement isdesigned to work with context-manager objects, which support a new method-basedprotocol.In short, the with/as statement is designed to be an alternative to a common try/finallyusage idiom; like that statement, it is intended for specifying termination-time or“cleanup” activities that must run regardless of whether an exception occurs in a processingstep. Unlike try/finally, though, the with statement supports a richer objectbasedprotocol for specifying both entry and exit actions around a block of code.<strong>Python</strong> enhances some built-in tools with context managers, such as files that automaticallyclose themselves, and thread locks that automatically lock and unlock, butprogrammers can code context managers of their own with classes, too.Basic UsageThis feature will not become an official part of <strong>Python</strong> until version 2.6. In <strong>Python</strong> 2.5,it is not yet available by default; it must be enabled with the special future import statementform we met in the modules part of this book (because of the two new reservedwords with and as, this feature is being introduced gradually, as usual):from _ _future_ _ import with_statementWhen you run this import statement in 2.5, you enable the new with statement, andits two reserved words. The basic format of the with statement looks like this:with expression [as variable]:with-block* In most cases, at least. As suggested in Part IV, if a function has to perform long-running or unrecoverableactions before it reaches the place where an exception will be triggered, you still might want to test for errors.Even in this case, though, be careful not to make your tests overly specific or restrictive, or you will limit yourcode’s utility.596 | Chapter 27: Exception Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!