[Tutor] How to model objects aimed to persistence?

Steven D'Aprano steve at pearwood.info
Thu Jun 17 01:47:13 CEST 2010


On Thu, 17 Jun 2010 06:39:44 am Knacktus wrote:

> So far, so good. But what is best practise to prepare this data for
> general persistence? It should be usable for serialisation to xml or
> storing to an RDBMS or ObjectDatabase ...

Oh wow, deja vu... this is nearly the same question as just asked a day 
or so ago, in the thread "conventions for establishing and saving 
default values for variables". The answer I give will be more or less 
the same as was already given in that thread:

Use ConfigParser for ini-style config files.

Use pickle or shelve for serialising arbitrary Python objects.

You probably shouldn't use marshal, as that's awfully limited and really 
only designed for serialising Python byte code.

You can roll your own XML solution using the various XML modules in the 
standard library, or use plistlib, an XML-based storage format borrowed 
from Mac OS X.

Or one of the other standard serialisers like JSON or YAML, although 
YAML is not in the standard library yet.

Or you can use any one of many different databases, although that's 
probably massive overkill.


> I guess I have to incorporate some kind of id for every object and
> use this as reference with some kind of look-up dictionary, 

"Have to"? Certainly not. If your data doesn't need an ID field, there's 
no need to add one just for serialisation. It would be a pretty bizarre 
serialiser that couldn't handle this:

{key: value}

but could handle this:

({id: key}, {key: value})



> but I 
> wouldn't like it and hope that there're some other sweet pythonic
> solutions?

There's a few... :)



By the way, looking at your class name:

class FavoritMovies(object):

I can forgive the American (mis)spelling of Favo(u)rite, but why have 
you dropped the E off the end of "favorite"? I'd almost think your 
keyboard was broken, but no, you have E in Movies and object.

Deliberate misspellings in class and variable names will cost you *far* 
more in debugging time when you forget to misspell the words than they 
will save you in typing. Trust me on this.


-- 
Steven D'Aprano


More information about the Tutor mailing list