Abstract Base Classes

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Nov 14 00:01:57 EST 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.

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 EnumException:
                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
idiom:

    import foo

    try:
        foo.do_stuff(bar)
    except FooException, e:
        special_error_handler(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