design question, metaclasses?

Aaron Brady castironpi at
Mon Apr 13 04:58:25 CEST 2009

On Apr 12, 4:53 pm, Darren Dale <dsdal... at> wrote:
> On Apr 12, 4:50 pm, Kay Schluehr <kay.schlu... at> wrote:
> > On 11 Apr., 20:15, Darren Dale <dsdal... at> wrote:
> > > I am working on a project that provides a high level interface to hdf5
> > > files by implementing a thin wrapper around h5py.
> > > I would like to
> > > generalize the project so the same API can be used with other formats,
> > > like netcdf or ascii files. The format specific code exists in File,
> > > Group and Dataset classes, which I could reimplement for each format.
> > > But there are other classes deriving from Group and Dataset which do
> > > not contain any format-specific code, and I would like to find a way
> > > to implement the functionality once and apply uniformly across
> > > supported formats.
> > Seems like you are doing it wrong. The classical OO approach is to add
> > more details / refining classes in subclasses instead of doing it the
> > other way round and derive the less specific classes from the more
> > specific ones.
> I think I am following the classical OO approach, refining details in
> subclasses. I just want a given subclass implementation describing a
> complex dataset to be able to work on top of multiple hierarchical
> file formats (like NetCDF or HDF5) by deriving from either NetCDF or
> HDF5 base classes that have an identical API. Those base classes
> encapsulate all the format-specific details, the subclasses allow a
> uniform image to be handled differently than a nonuniform image with a
> mask (for example). Maybe I should be delegating rather than
> subclassing.

You made me think of the 'mixin' design pattern, also known as
multiple inheritance.  The subclass derives from multiple classes.
One is the domain-specific description of the data class; the other is
the file format.

class NetCDF_DataA_Writer( NetCDF_Writer, DataA_Description ):

The two classes can't have conflicting method names, however; or
you'll have to resolve them by hand, or assign them unique names.  In
this example, the subclass would favor the first super class, and you
could access the second super class with special names.  It kind of
makes uniform access unreliable.

class NetCDF_DataA_Writer( NetCDF_Writer, DataA_Description ):
    data_write= DataA_Description.write
    file_write= NetCDF_Writer.write

The standard library has a couple of examples of this, as I recall,
such as the UDPServerMixin (sp).

More information about the Python-list mailing list