What's the use of the else in try/except/else?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu May 14 07:03:16 CEST 2009

On Thu, 14 May 2009 00:39:35 -0400, ma wrote:

> A really great use for try/except/else would be if an object is
> implementing its own __getitem__ method, so you would have something
> like this:
> class SomeObj(object):
>     def __getitem__(self, key):
> 		try:
> 			#sometype of assertion here based on key type
> 		except AssertionError, e:
> 			raise TypeError, e #invalid type

Why raise AssertionError only to catch it and raise TypeError? Why not 
just raise TypeError in the first place?

If you're thinking of writing this:

assert isinstance(key, whatever)

you should be aware that when Python is run with the -O flag (optimize), 
all asserts are disabled, and so your error checking code will not run 
and your program will crash and burn in a horrible flaming mess.

[steve at wow-wow ~]$ python -O
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> assert None is 2

The assert statement is not for runtime error checking. assert is for 
checking your program logic and invariants. If you've ever written a 
comment like:

# When we get here, then x will always be greater than 3.

(or something like that), that's a great candidate for an assertion:

assert x > 3, "x is unexpectedly less than or equal to three"

For error checking, you should do something like this:

if not isinstance(key, whatever):
    raise ValueError

rather than:

    if not isinstance(key, whatever):
        raise AssertionError
except AssertionError:
    raise ValueError


More information about the Python-list mailing list