empty lists vs empty generators
Jeremy Bowers
jerf at jerf.org
Mon May 2 21:32:04 EDT 2005
On Mon, 02 May 2005 16:14:57 -0700, Brian Roberts wrote:
> Q1: Is there a better or alternate way to handle this? Q2: Is there a way
> that handles both lists and generators, so I don't have to worry about
> which one I've got?
Are you in control of your generators? You could put a method on them that
tells if there is anything in them by manually implementing the .next()
call.
The other thing you could do is a generator wrapper that can tell for you,
but you'll lose some performance:
class EmptyGeneratorDetector(object):
"""Provides a method you can call to detect an empty
generator. You should probably name this class something
shorter.
Check if the generator is empty after construction by looking at
the isEmpty property."""
def __init__(self, generator):
self.generator = generator
self.isEmpty = False
self.givenFirst = False
try:
self.firstItem = generator.next()
except StopIteration:
self.isEmpty = True
def next(self):
if self.isEmpty:
raise StopIteration
if not self.givenFirst:
self.givenFirst = True
return self.firstItem
else:
return self.generator.next()
def __iter__(self):
return self
In action:
Python 2.3.5 (#1, Mar 3 2005, 17:32:12)
[GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from genwrap import *
>>> def emptyGenerator():
... raise StopIteration
... yield None
...
>>> def nonEmptyGenerator():
... yield 1
... yield 2
... yield 3
...
>>> e = emptyGenerator()
>>> n = nonEmptyGenerator()
>>> E = EmptyGeneratorDetector(e)
>>> N = EmptyGeneratorDetector(n)
>>> E.isEmpty
True
>>> N.isEmpty
False
>>> for i in E:
... print i
...
>>> for i in N:
... print i
...
1
2
3
>>>
It is tested as much as you see it above :-)
(I recall a lengthy discussion of the best way to create an empty iterator
a while back, and that was not the winner. But it will do for now.)
More information about the Python-list
mailing list