Should I prefer an external database
ianb at colorstudy.com
Tue Apr 22 10:54:41 CEST 2003
On Tue, 2003-04-22 at 03:11, Brian Elmegaard wrote:
> I am working on a script for organizing a program for a conference. I
> started out using a connection to mySQL, but then I thought that it
> would be easier to keep it within python. So I implemented a class:
> class Paper:
> def __init__(title,author,session):
> I then have a list to which each new paper instance is appended. I can
> sort by any of the paper instances variables by using the
> decorate-sort-undecorate method.
> I now have it working, but I probably could do better, so:
> Is this a more pythonic way to implement this?
More Pythonic? Eh... I would say that's fine, from a purely "What's
Pythonic" view. Is there a *better* way? Well, there's *always* a
better way... ;)
> To do a select I think I need to use for loops specifying the names of
> the variables, i.e:
> for paper in paperlist:
> if paper.session=='foo':
> print paper.title
> Probably this might be done more elegantly, but how do I know which
> variables (database columns) the instance has?
You could try a number of techniques for making searches easier to use.
result = 
for paper in paperlist:
matched = True
for key, value in kw.items():
if getattr(paper, key) != value:
matched = False
if matched: result.append(paper)
Then you can do search(title="foo", author="bar"), for instance.
You can do lots just with list comprehension, like:
result = [p for p in paperlist if p.session == 'foo']
For particular searches you can do all sorts of indexing, mostly a
matter of creating dictionaries of commonly searched-for keys.
> Would I be better of with a list of list than with a list of class
No, I think instances are better.
> What about a class of classes? Could such be made and inherit from the
> list class to support index and sort?
You could, say, store all the instances in a class variable, then use
class methods to search them. Then you could index the objects as you
find it necessary, hiding the indexing in the functions.
Now, that all said, you might want an external database with an
object-relational mapper. Using SQLObject (plug: http://sqlobject.org),
you'd do it like:
from SQLObject import *
__connection__ = MySQLConnection(user=...)
# or use Postgres, SQLite, or a DBM backend
_columns = [StringCol('title'),
(this will look a little cleaner in the next version)
Then use it like:
for paper in Paper.select(AND(Paper.q.title == 'foo',
for paper in Paper.selectBy(title='foo', author='bar'):...
Plus you get persistence. A database like SQLite adds code
dependencies, but no environment dependencies, so maybe that's what you
are looking for (SQLite just stores its database in a single file and
Ian Bicking ianb at colorstudy.com http://colorstudy.com
PGP: gpg --keyserver pgp.mit.edu --recv-keys 0x9B9E28B7
4869 N. Talman Ave., Chicago, IL 60625 773-275-7241
More information about the Python-list