Python Mystery Theatre -- Episode 1: Exceptions

Raymond Hettinger vze4rx4y at
Sat Jul 12 08:56:52 CEST 2003

For your amusement and edification, I'm working on a
series of Python puzzles designed to highlight areas of
the language known only to those who have read the
docs more than once.

Each of the following sections contains a code snippet
that someone, somewhere might find a little mysterious.

Your goal is to sleuth through the code, identify what
was expected versus what really happened, and to
explain it briefly so that others will find it blindingly

The mysteries are not difficult, but I would suprised
if most readers didn't learn something new along the way.

Of course, if you are a potential bot, then these mysteries
will be very difficult because all you will see is the code
operating as designed, implemented, documented and tested.

When you post your results, I would be interested in
knowing whether you already knew what was going
on or whether you had to resort to:

* reading other posts
* googling
* experimenting
* or worse, re-reading the docs

Raymond Hettinger

ACT I ---------------------------------------
>>> s = list('abc')
>>> try:
...     result = s['a']
... except IndexError, TypeError:
...     print 'Not found'

Traceback (most recent call last):
  File "<pyshell#11>", line 2, in -toplevel-
    result = s['a']
TypeError: list indices must be integers

ACT II --------------------------------------------
>>> class MyMistake(Exception):
...     pass

>>> try:
...     raise MyMistake, 'try, try again'
... except MyMistake, msg:
...     print type(msg)

<type 'instance'>

ACT III --------------------------------------------
>>> class Prohibited(Exception):
...     def __init__(self):
...         print 'This class of should never get initialized'
>>> raise Prohibited()
This class of should never get initialized

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in -toplevel-
    raise Prohibited()
Prohibited: <unprintable instance object>
>>> raise Prohibited
This class of should never get initialized

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in -toplevel-
    raise Prohibited
Prohibited: <unprintable instance object>

ACT IV -----------------------------------------------
>>> module = 'Root'
>>> try:
...     raise module + 'Error'
... except 'LeafError':
...     print 'Need leaves'
... except 'RootError':
...     print 'Need soil'
... except:
...     print 'Not sure what is needed'

Not sure what is needed

ACT V -----------------------------------------------
>>> try:
...     raise KeyError('Cannot find key')
... except LookupError, msg:
...     print 'Lookup:', msg
... except OverflowError, msg:
...     print 'Overflow:', msg
... except KeyError, msg:
...     print 'Key:', msg

Lookup: 'Cannot find key'

More information about the Python-list mailing list