On Sun, 17 Apr 2005 19:56:10 -0700, Brian Sabbey
<[EMAIL PROTECTED]> wrote:
>I also wouldn't do it that way.  I don't see a class as being much better, 
>though.  If I understand you correctly, with classes you would have 
>something like:
>
>p = Pickled('pickled.txt')
>p.load()
>p.data.append('more data')
>p.data.append('even more data')
>p.dump()

The load and dump would be private to the data class object. Here's a
more complete example.  

import pickle
class PickledData(object):
        def __init__(self, filename):
                self.filename = filename
                self.L = None
                try:
                        self._load()
                except IOError:
                        self.L = []
        def _load(self):
                f = open(self.filename, 'r')
                self.L = pickle.load(f) 
                f.close()
        def _update(self):
                f = open(self.filename, 'w')
                pickle.dump(self.L, f)
                f.close()                       
        def append(self, record):
                self.L.append(record)
                self._update()
        # add other methods as needed ie.. get, sort, clear, etc...

pdata = PickledData('filename')

pdata.append('more data')
pdata.append('even more data')

print pdata.L
['more data', 'even more data']


>This has the same issues as with opening and closing files:  losing the 
>'dump', having to always use try/finally if needed, accidentally 
>re-binding 'p', significantly more lines.  Moreover, class 'Pickled' won't 
>be as readable as the 'pickled_file' function above since 'load' and 
>'dump' are separate methods that share data through 'self'.

A few more lines to create the class, but it encapsulates the data
object better. It is also reusable and extendable.

Cheers,
Ron

>The motivation for thunks is similar to the motivation for generators-- 
>yes, a class could be used instead, but in many cases it's more work than 
>should be necessary.
>
>-Brian


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to