Best way to do data source abstraction

bruno at modulix onurb at xiludom.gro
Thu Jun 1 05:20:22 EDT 2006


Arthur Pemberton wrote:
> What is the best way to do data source abtraction? For example have
> different classes with the same interface, but different
> implementations.
> 
> I was thinking of almost having classA as my main class, and have
> classA dynamically "absorb" classFood into to based on the extension
> of the input file received by classA. But this doesn't seem possible.

Could you explain more accurately what you're trying to do ? FWIW, it
seems that a plain old factory function would do ?

class DatasourceAbstraction(object):
  """ base class, factoring common stuff """
  # implementation here

class JpegFile(DatasourceAbstraction):
  # ....


class PdfFile(DatasourceAbstraction):
  # ....

class TxtFile(DatasourceAbstraction):
  # ....

# etc
_classes = {
  'jpg' : JpegFile,
  'txt' : TxtFile,
  'pdf' : PdfFile,
  # etc..
}

def Datasource(inputfile):
  ext = os.path.splitext(inputfile)
  return _classes.get(ext, <SomeDefaultClassHere>)(inputfile)

The fact that there's no 'new' keyword in Python, and that classes are
callable objects acting as factories means that it's a no-brainer to use
a plain function (eventually disguised as a Class - the client code just
doesn't care !-) as factory...

Now if I missed the point, please give more explanations...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list