iterator? way of generating all possible combinations?
Scott David Daniels
scott.daniels at acm.org
Tue May 30 18:24:50 EDT 2006
akameswaran at gmail.com 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
scott.daniels at acm.org
More information about the Python-list
mailing list