"pickle" vs. f.write()

Martin Miller mmiller at tx3.com
Tue Feb 1 07:05:57 EST 2005


On 1/26/05 at 1:48 pm, Terry Reedy wrote:
> For basic builtin objects, repr(ob) generally produces a string that when 
> eval()ed will recreate the object.  IE
> eval(repr(ob) == ob # sometimes

I've found extending this property to your own classes often fairly easy
to implement (and useful). For example:

> class person:
>     def __init__(self, name="", age=0, friends=None, comment=""):
>         if friends is None:
>             friends = []
>         self.name, self.age, self.friends, self.comment = name, age, friends, comment
> 
>     def __repr__(self):
>         return ("person(" + repr(self.name) + ", " + repr(self.age) + ", " +
>                 repr(self.friends) +  ", " + repr(self.comment) + ")")
> 
> me = person()
> 
> print "me =", repr(me)

Which produces the following output:
   me = person('', 0, [], '')


In addition, the following constructs are possible:

> family = [
>     person("Martin", 50, ["Matt"], "eldest son"),
>     person("Matt", 43, ["Martin"], "youngest son"),
>     person("Merry", 72, ["Martin", "Matt"], "mother"),
>     person("Luther", 82, ["Merry"], "father")
> ]
> 
> print "family =", repr(family)

Which output the following:
family = [person('Martin', 50, [], 'eldest son'), person('Matt', 43,
['Martin'], 'youngest son'), person('Merry', 72, ['Martin', 'Matt'],
'mother'), person('Luther', 82, ['Merry'], 'father')]

Basically this approach allows you to store your data in Python source
files -- which you can then import or execfile. The files can also
contain comments and are relatively easy to edit by hand. In addition
they're portable.

Best,
Martin





More information about the Python-list mailing list