Boolean value of generators
Albert Hopkins
marduk at letterboxes.org
Thu Oct 14 14:43:29 EDT 2010
On Thu, 2010-10-14 at 10:16 +0100, Tony wrote:
> I have been using generators for the first time and wanted to check for
> an empty result. Naively I assumed that generators would give
> appopriate boolean values. For example
>
> def xx():
> l = []
> for x in l:
> yield x
>
> y = xx()
> bool(y)
>
As people have already mentioned, generators are objects and objects
(usually) evaluate to True.
There may be times, however, that a generator may "know" that it
doesn't/isn't/won't generate any values, and so you may be able to
override boolean evaluation. Consider this example:
class DaysSince(object):
def __init__(self, day):
self.day = day
self.today = datetime.date.today()
def __nonzero__(self):
if self.day > self.today:
return False
return True
def __iter__(self):
one_day = datetime.timedelta(1)
new_day = self.day
while True:
new_day = new_day + one_day
if new_day <= self.today:
yield new_day
else:
break
g1 = DaysSince(datetime.date(2010, 10, 10))
print bool(g1)
for day in g1:
print day
g2 = DaysSince(datetime.date(2011, 10, 10))
print bool(g2)
for day in g2:
print
day
> True
> 2010-10-11
> 2010-10-12
> 2010-10-13
> 2010-10-14
> False
More information about the Python-list
mailing list