On Sun, 17 Apr 2005 15:02:12 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote:
Brian Sabbey wrote: > I'm kicking myself for the first example I gave in my original post in > this thread because, looking at it again, I see now that it really gives > the wrong impression about what I want thunks to be in python. The > 'thunkit' function above shouldn't be in the same namespace as the thunk. > It is supposed to be a re-usable function, for example, to acquire and > release a resource. On the other hand, the 'foo' function is supposed to > be in the namespace of the surrounding code; it's not re-usable. So your > example above is pretty much the opposite of what I was trying to get > across. This would explain why I'm having trouble seeing it then. > 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? This might be the non-thunk version of the above. 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. >> def with_file: # no argument list, local group. >> f = open(filename) >> t = callback(f) >> f.close >> >> def my_read(f): >> return f.read() >> >> callback = my_read >> filename = 'filename' >> do with_file > > This wouldn't work since with_file wouldn't be re-usable. It also doesn't > get rid of the awkwardness of defining a callback. As long as the name with_file isn't rebound to something else it could be used as often as needed. I admit there are better ways to do it though. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list