473,387 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Best way to do data source abstraction

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.

Please advise.

Thank you.

--
To be updated...
Jun 1 '06 #1
4 1811
Arthur Pemberton enlightened us with:
What is the best way to do data source abtraction?
That depends on your data source. For files, file-like objects are an
abstraction. For databases there is PEP 249.
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.


You don't explain the most important part - "absorb". What does that
mean? And what does it mean to have classA "almost" as your main
class?

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Jun 1 '06 #2
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 'o****@xiludom.gro'.split('@')])"
Jun 1 '06 #3
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.

Please advise.

Thank you.


The best method I've found is to have a class that abstracts
the data and presents the values from the data source via
class attributes. If you also implement it as an iterator
(e.g. give it __iter__ and __next__ methods), you can easily
iterate over the resultset from each data source. With this
method I've abstracted data in CSV files, fixed ASCII files,
SQL tables, Excel Spreadsheets, tab delimited files that are
members of a .ZIP archive, you name it.

Short example (not tested):
class foo:
'''
Class to abstract tab delimited files
'''
def __init__(self, filepath, columnnames):
self.fp=open(filepath, 'r')
self.columnnames=columnnames
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next line from file
#
try: line=self.fp.next()
except StopIteration:
self.fp.close()
raise

#
# Decode the tab delimited line into its parts
#
line=line.rstrip()
if not line: raise StopIteration
values=line.split('\t')
print "values=", values
l=zip(self.columnnames, values)
print l
for column, value in l:
setattr(self, column, value)

return

if __name__ == "__main__":
obj=foo('abc.txt', ['name', 'address1', 'address2', 'city', 'state', 'zip'])

for entry in obj:
print ""
print "Name........", obj.name
print "Address1....", obj.address1
print "Address2....", obj.address2
print "City........", obj.city
print "State.......", obj.state
print "Zip.........", obj.zip
-Larry Bates
Jun 1 '06 #4
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.

Please advise.

Thank you.


The best method I've found is to have a class that abstracts
the data and presents the values from the data source via
class attributes. If you also implement it as an iterator
(e.g. give it __iter__ and __next__ methods), you can easily
iterate over the resultset from each data source. With this
method I've abstracted data in CSV files, fixed ASCII files,
SQL tables, Excel Spreadsheets, tab delimited files that are
members of a .ZIP archive, you name it.

Short example (not tested):
class foo:
'''
Class to abstract tab delimited files
'''
def __init__(self, filepath, columnnames):
self.fp=open(filepath, 'r')
self.columnnames=columnnames
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next line from file
#
try: line=self.fp.next()
except StopIteration:
self.fp.close()
raise

#
# Decode the tab delimited line into its parts
#
line=line.rstrip()
if not line: raise StopIteration
values=line.split('\t')
print "values=", values
l=zip(self.columnnames, values)
print l
for column, value in l:
setattr(self, column, value)

return

if __name__ == "__main__":
obj=foo('abc.txt', ['name', 'address1', 'address2', 'city', 'state', 'zip'])

for entry in obj:
print ""
print "Name........", obj.name
print "Address1....", obj.address1
print "Address2....", obj.address2
print "City........", obj.city
print "State.......", obj.state
print "Zip.........", obj.zip
-Larry Bates

Jun 1 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Ed Fair | last post by:
Hi, I'm a long-time C programmer, I've started making the transition to "real C++" recently. I am puzzled about how to write a factory method. Any suggestions, pointers or references to...
21
by: ambika | last post by:
Hello, I have a very basic doubt. Why is C called a structured programming language??why structured? C++ is called a Object Oriented language 'cos it obeys the OOP's concepts..Why is C called a...
9
by: Anand Vardhan | last post by:
Hi Could anyone tell me if there is any way to do data abstraction in C or use object oriented methods. I was thinking about using structures but I am getting no where. Regards.
4
by: mharness | last post by:
Hello All, I've defined a number of classes that currently only include public variable declarations. I've been reluctant to add subroutines and functions for fear of taking a performance hit...
3
by: S. Lorétan | last post by:
Hi guys, I'm coding an application connected to a database. I have some clients that use this program with 2 or 3 computers, and I use MsSQL Express for them. But if the client needs more...
63
by: time.swift | last post by:
Coming from a C++ / C# background, the lack of emphasis on private data seems weird to me. I've often found wrapping private data useful to prevent bugs and enforce error checking.. It appears...
13
by: G | last post by:
Hello, Looking for opinions on a fairly simple task, new to ASP.net (C#) and want to make sure I do this as efficiently as possible. I have a web based form, and I need to run some SQL before...
17
Motoma
by: Motoma | last post by:
This article is cross posted from my personal blog. You can find the original article, in all its splendor, at http://motomastyle.com/creating-a-mysql-data-abstraction-layer-in-php/. Introduction:...
2
by: subramanian100in | last post by:
Is my following understanding correct ? Data abstraction means providing the interface - that is, the set of functions that can be called by the user of a class. Information hiding means...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.