Ron_Adam wrote:
def pickled_file(thunk, name): f = open(name, 'r') l = pickle.load(f) f.close() thunk(l) f = open(name, 'w') pickle.dump(l, f) f.close()
Now I can re-use pickled_file whenever I have to modify a pickled file:
do data in pickled_file('pickled.txt'): data.append('more data') data.append('even more data')
In my opinion, that is easier and faster to write, more readable, and less bug-prone than any non-thunk alternative.
The above looks like it's missing something to me. How does 'data' interact with 'thunk(l)'? What parts are in who's local space?
Your example below explains it well, with 'data' renamed as 'L'. The scope of bindings are the same in both examples, with the exception that 'data' is in the outermost namespace in the above example, and 'L' is local to the function 'data_append' in the below example.
This might be the non-thunk version of the above.
yes
def pickled_file(thunk, name): f = open(name, 'r') l = pickle.load(f) f.close() thunk(l) f = open(name, 'w') pickle.dump(l, f) f.close()
def data_append(L): L.append('more data') L.append('still more data')
pickled_file(data_append, name)
I don't think I would do it this way. I would put the data list in a class and add a method to it to update the pickle file. Then call that from any methods that update the data list.
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()
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'.
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