Style for overwritten methods of abstract classes

Stefan Schwarzer s.schwarzer at ndh.net
Thu Jan 3 13:45:02 EST 2002


Hello all :)

As an example, I have an abstract base class CacheBase which provides
an interface to a persistent storage. All methods _could_ be either
overwritten (__init__, __del__) or _have to_ be provided (__getitem__,
__setitem__). Initially, I wrote

class CacheBase:
    '''Represents an abstract interface for the URL/value
    storage.
    
    Overwrite __init__, __getitem__, __setitem__, and
    __del__ to customize the class.'''

    def __init__(self):
        pass

    def __getitem__(self, url):
        '''Return an abstract value from the cache for the
        given URL. Return None if the URL is not in the
        cache.'''
        return None

    def __setitem__(self, url, value):
        '''Set an abstract value (usable for comparisons with
        a remote URL) for the URL.'''
        pass

    def __del__(self):
        '''Clean up.'''
        pass

I personally like this as an overview of which methods should be
defined in derived classes. On the other hand, it may be considered
verbose to write all of the above given that the methods would have
to be overwritten anyway.

Another aspect is that the "noop implementations" of __getitem__ and
__setitem__ could actually obscure bugs if somebody forgets to overwrite
the methods in derived classes.

So I can think of three different approaches:
1. write the code as above
2. merely describe the implementation/interfaces (e. g. in the class
   docstring or in a comment); write no code
3. use code but let the abstract methods raise NotImplementedError
   instead of providing a default behaviour which might be useless
(4. Are there others?)

In the light of 2., __del__ might be a special case because it may be
very important for clean-up and at the same time might go unnoticed
for a while because Python will use its default behaviour regardless
if __del__ had been defined in the abstract class or not.

Which approach would you prefer and why? Can you think of criteria/cases
where you would use one approach and in another case another approach?

Thanks in advance for your replies.

Stefan



More information about the Python-list mailing list