Abstract Base Classes

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Nov 14 06:08:26 CET 2005

Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> I want my modules to (sometimes) define an abstract base exception
> class, that all other exceptions in that module inherit from.

[re-posting with the implementation properly foo-ified]

Not a whole lot of feedback on this, so here's the implementation I
decided upon.

    class FooException(Exception):
        """ Base class for all exceptions in this module """
        def __init__(self):
            if self.__class__ is FooException:
                raise NotImplementedError, \
                    "%s is an abstract class for subclassing" % self.__class__

    class FooBarTypeError(TypeError, FooException):
        """ Raised when the foo gets a bad bar """

    class FooDontDoThatError(AssertionError, FooException):
        """ Raised when the foo is asked to do the wrong thing """

This allows the exceptions for the module to behave similarly to their
leftmost base exception; but because they all inherit from the
abstract base class exception for the module, it also allows for this

    import foo

    except FooException, e:

Any more comment on this technique? Any other significant use cases
for abstract base classes?

 \     "For man, as for flower and beast and bird, the supreme triumph |
  `\   is to be most vividly, most perfectly alive"  -- D.H. Lawrence. |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list