iterator? way of generating all possible combinations?

Scott David Daniels scott.daniels at acm.org
Tue May 30 16:59:59 EDT 2006


akameswaran at gmail.com wrote:
> Scott David Daniels wrote:
> 
>> This works with "iterables" (and produces), rather than "iterators",
>> which is vital to the operation.
>>
>> --Scott David Daniels
>> scott.daniels at acm.org
> 
> Sorry, it doesn't.  It works with strings.  It doesn't work with file,
> it doesn't work with iterators I have created.

Sorry, "re-iterables".  A file re-iterable is:

     class FileReIterable(object):
         def __init__(self, file):
             if isinstance(file, basestring):
                 self.file = open(file, 'rU')
             else:
                 self.file = file
         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 __init__(self, file):
             if isinstance(file, basestring):
                 self.file = open(file, 'rU')
             else:
                 self.file = file
         def __iter__(self):
             self.file.seek(0)
             for line in self.file:
                 nextpos = self.file.tell()
                 yield line
                 self.file.seek(nextpos)

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list