Hi,
I have right now some code that initializes a few 'bootstrap' objects
for a system. Right now the database is created by a separate script.
Each add-on module needs to be run later to save is own objects. This
causes some problems, as I need to re-run all addo-on modules when a
single one changes. One of the reasons is that the initialization code
is simple-minded: it only tries to create the required objects, and it
does not check if the object already exists, or if it was modified. I
really don't think that it should be necessary for me to trap all
calls into try: except : , or to check explicitly for the existence of
the objects.
My proposal is to add two new classmethods to the SQLObJect class:
1. The 'overwrite' method checks if the object exists, and overwrites
it with a new version. It uses the alternate keys to check if the
object exists. (this is based on the assumption that I can't know the
ID beforehand). The method signature is:
def overwrite(cls, overwriteKey=None, **kw):
"""
Creates a new object in the table, and overwrites the old version
if it exists. overwriteKey is the name of the alternateKey to be
used to check for existence of the object.
"""
2. The 'setdefault' constructor is like the dictionary method of the
same name. It reads the object from the database (again, using the
alternate key to find it); if it does not exists, it creates a new
object with the values supplied. The name was chosen because of the
name of the equivalent method in the std lib, but it can be changed to
something more meaningful.
def setdefault(cls, setdefaultKey=None, **kw):
"""
Reads an object from the table, and creates a new one with
default values if the object was not found. setdefaultKey is
the name of the alternateKey to be used to check for
existence of the object.
"""
I don't know if this idea is generic enough to deserve inclusion in
the core library. Perhaps a FAQ entry, or an auxiliary library, could
be used. What I know is that these methods add some convenience and
make code easier to read & write.
And yes, I volunteer to write it. :-)
--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: car...@gm...
mail: car...@ya...
|