Scott David Daniels wrote: > [EMAIL PROTECTED] wrote: > > Scott David Daniels wrote: > >> Sorry, "re-iterables". A file re-iterable is: > >> > >> class FileReIterable(object): ... > >> def __iter__(self): > >> self.file.seek(0) > >> return iter(self.file) > >> > >> This works if-and-only-if it is only in use once at a time. > >> If you have multiple simultaneous accesses, you need to do > >> something like: > >> > >> class FileReIterable2(object): ... > >> def __iter__(self): > >> self.file.seek(0) > >> for line in self.file: > >> nextpos = self.file.tell() > >> yield line > >> self.file.seek(nextpos) > > > > Since I was doing this as a self education excercise. When you say is > > in use once and only once, you mean I can only use a single instance of > > the class? > No. This works: > > f1 = FileReIterable("one.file") > f2 = FileReIterable("another.file") > ... free uses of ... > > This does not "work": > > gen = FileReIterable("one.file") > > for a in gen: > for b in gen: > print a, b > > This does "work": > > gen = FileReIterable2("one.file") > > for a in gen: > for b in gen: > print a, b > > That is, any instance of FileReIterable must not be used in a > context where it may be in the midst of iterating a file, gets > used to produce a result, and then must produce a result from > the original iteration. > > If you think about what must happen to the file read pointer, > the reason for all of this should become clear. > > --Scott David Daniels > [EMAIL PROTECTED]
Thanks for the explanation, the issue of the file pointer was pretty clear - it's why I created multiple files. I just misunderstood what you meant by use only one. What I did miss at first was the fact that the file object is not re-iterable. Just plain dumb oversite. Of course in the end I'm actually more concerned with writing my own iterators or generators. I was to busy thinking my errors were in the recursion to look at the iterable/reiterable issue. This is a working version of the die class I started this thread with. class die(object): def __init__(self,sides): self.sides=sides self.next = 1 def next(self): if self.next <= self.sides: current = self.next self.next +=1 return current else: self.next=1 raise StopIteration def __iter__(self): return self -- http://mail.python.org/mailman/listinfo/python-list