[Python-Dev] code blocks using 'for' loops and generators
Steven Bethard
steven.bethard at gmail.com
Sun Mar 13 02:01:50 CET 2005
Brian Sabbey <sabbey at u.washington.edu> wrote:
> I agree that this is a confusing way to use generators. But it is the
> expected way to use "code blocks" as found in other languages. It would
> take some getting used to that 'for' can be used this way, but I think it
> would be worth it.
I guess I need some more convincing... I don't find your approach[*], e.g.
def pickled_file(name):
f = open(name, 'r')
data yield pickle.load(f)
f.close()
f = open(name, 'w')
pickle.dump(data, f)
f.close()
for data in pickled_file('greetings.pickle'):
data.append('hello')
data.append('howdy')
continue data
any clearer than, say:
class PickledFile(object):
def __init__(self, name):
self.name = name
f = open(self.name, 'r')
self.data = pickle.load(f)
f.close()
def close(self):
f = open(self.name, 'w')
pickle.dump(self.data, f)
f.close()
p = PickledFile('greetings.pickle')
p.data.extend(['hello', 'howdy'])
p.close()
Note that I'm not using the iteration construct (for-in) because I'm
not really doing an iteration here. Pehaps I could be taught to read
for-in otherwise, but without an obvious benefit for doing so, I'm
really not inclined to.
Steve
[*] I've renamed your "l" to "data". The first time I read your post,
it looked even more confusing to me because "l" (lower case L) is
rendered too similarly to "|" (or-bar) in my browser.
--
You can wordify anything if you just verb it.
--- Bucky Katt, Get Fuzzy
More information about the Python-Dev
mailing list